我正在开发一个MVC 3 Razor Web App,其中存储了多个类别的对象的详细信息。(车辆、房屋、仪器等)。所有对象共享一些公共数据(标题、描述等)和一些特定于其所属类别的细节。Category列表预计会增长,并且考虑到降低可维护性,我们希望重用相同的Add Object向导。该向导基于以下实现。
http://afana.me/post/create-wizard-in-aspnet-mvc-3.aspx
在多步骤向导过程中,最后一步允许用户输入类别特定的详细信息(车辆的型号、制造商、VIN等)。目前,我已经将这最后一步设想为使用AJAX的局部视图。因此,我们实际上将拥有多个反映特定类别的局部视图,但共享向导代码的其余部分。
我的通用模型对象如下所示
public class AssetView
{
[Required]
public string Title
{
get;
set;
}
[Required]
public string Description
{
get;
set;
}
// Few more generic fields here
public SpecificAsset AssetDetails { get; set; }
}复杂属性AssetDetails由每种类型的局部视图表示。因此,PartialView "MotorDetails“将包含MotorAsset类型的强类型模型,声明如下。
public class MotorAsset : SpecificAsset
{
[Required]
public string Transmission
{
get;
set;
}
[Required]
public string Make
{
get;
set;
}
}实际的验证要复杂得多,但我省略了这些,以便更容易理解。
主向导页声明为
@model AssetView
.....
<div class="wizard-step">
....
</div>
<div class="wizard-step">
....
</div>
<div class="wizard-step">
@{Html.RenderPartial("_MotorCreate", Model.AssetDetails);
</div>电机局部视图为
@model MotorAsset我的问题是,我如何在此场景中完成模型验证(或者是否可以使用),因为最后一步不是在视图页面中,而是在部分视图中。
发布于 2011-01-30 00:40:48
为什么不求助于简单的类继承(OOP范例)而不是在AssetView上拥有属性AssetDetails呢?
而不是您现在所拥有的,而应该声明
AssetView (通用属性) -> MotorView继承AssetView (特定属性)
如下所示:
public class AssetView {
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
// Few more generic fields here
}
public class MotorView : AssetView {
...
}
@model MotorView // you still have access to the AssetView's properties in your view and in your controller actions如果您想让它保持现在的状态,那么使用EditorFor()并在共享文件夹中创建一个EditorFor模板,然后强烈地将其输入到MotorAsset (或者SpecificAsset,如果您希望它更通用)。
然后像这样渲染它:
@Html.EditorFor(model=>model.AssetDetails)这将使控制器能够验证它,并将其自动绑定到AssetView中的属性。HTH
https://stackoverflow.com/questions/4837901
复制相似问题