我已经查看了这里的示例,但我并不完全理解MVC中的视图和部分视图。
我有一个名为“Edit.cshtml”的视图,其代码如下:
<div class="row">
<div class="form-group">
@Html.LabelFor(model => model.AddressLine1, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-4">
@Html.EditorFor(model => model.AddressLine1, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.AddressLine1, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.AddressLine2, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-4">
@Html.EditorFor(model => model.AddressLine2, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.AddressLine2, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="form-group">
@Html.LabelFor(model => model.City, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-4">
@Html.EditorFor(model => model.City, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.City, "", new { @class = "text-danger" })
</div>
@Html.LabelFor(model => model.StateAbbreviation, "State", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-4">
@Html.DropDownList("StateAbbreviation", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.StateAbbreviation, "", new { @class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-6">
</div>
@Html.LabelFor(model => model.ZipCode, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-4">
@Html.EditorFor(model => model.ZipCode, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.ZipCode, "", new { @class = "text-danger" })
</div>
</div>
</div>
由于此代码将在具有相同格式的多个模型上使用,因此我想为其创建一个简单的局部视图。 _AddressPartial.cshtml中的代码正是上面列出的内容。在视图中,我将其称为:
@Html.Partial("_AddressPartial")
它不起作用。我得到一个HttpCompileException。我假设我需要将我的Model对象发送给它,但我不确定该模型是什么? ViewBag?我的问题是,我需要传递给它什么?
答案 0 :(得分:2)
首先为部分视图声明模型类型
@model MyNamespace.MyModel
由于您在不同模型中重复使用此视图,因此会为视图指定基本类型或界面。
public interface IMyModel
{
string AddressLine1 { get; set; }
string City { get; set; }
...
}
然后是模型声明
@model MyNamespace.IMyModel
现在您可以使用具有可重用视图的不同模型
public class FooModel : IMyModel
{
public int FooId { get; set; }
// IMyModel properties
public string Address1 { get; set; }
public string City { get; set; }
}
使用
@model MyNamespace.FooModel
@Html.Partial("_AddressParital", Model)
或
@Html.Partial("_AddressPartial", new FooModel { ... })
答案 1 :(得分:0)
只需在部分视图名称之后传递模型。
@Html.Partial("_AddressPartial", model)
这将传递当前页面的模型,您可能希望仅根据您的模型传递其中一些,例如
@Html.Partial("_AddressPartial", model.Address)
注意:在局部视图中,您需要定义模型的类型......
@model MyNamespace.AddressModel