您应该为其他模型使用一些 prtialviews。您有主模型的主视图。在该视图中,您可以对它们的模型和验证有一些局部视图。
- - - - - - - - - - - - - - - - - - - 编辑:
正如其他人所说,最好使用视图模型并将模型相互结合。但正如你所愿,我在我的 Github 帐户上为你创建了一个示例项目:
https://github.com/bahman616/ASPNET_MVC_multiple_models_in_a_view_with_partialview.git
这是该项目的简化代码:
这里有两个模型:
public partial class Person
{
public int ID { get; set; }
[Required]
public string Name { get; set; }
}
public partial class Company
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
我想在一个视图中同时创建视图,所以这是父视图:
@model ASP_NET_MVC_Multiple_Models_In_A_View.Models.Person
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Create","Person")) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@{Html.RenderAction("_CompanyCreate", "Company");}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
这是部分观点:
@model ASP_NET_MVC_Multiple_Models_In_A_View.Models.Company
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
@using (Html.BeginForm("_CompanyCreate","Company")) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Company</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>