我有一个强类型视图,可以创建如下的表单字段:
@Html.TextBoxFor(x => x.Name, new { @class = "form-control" })
很好,上面的lambda表达式中的X与我使用' Name'的属性创建的I类相关。
如何使用相同的视图但是可以访问其他类的属性?例如,如果您想象我还有另一个名为UserDetails的类,并且电子邮件地址是其中的一个属性。我该怎么做:
@Html.TextBoxFor(x => x.Email, new { @class = "form-control" })
在同一个强类型视图中?
答案 0 :(得分:2)
在asp.net mvc中,你将模型传递给这样的视图:
public ActionResult Base()
{
return View(new DerviedOne());
}
以下是您的模型定义:
public class BaseModel
{
public int Id { get; set; }
}
public class DerviedOne : BaseModel
{
public string Email { get; set; }
}
public class DerviedTwo : BaseModel
{
public string Name { get; set; }
}
然后你必须创建三个视图:
基本视图:
@using Models
@model Models.BaseModel
@{
ViewBag.Title = "Base";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Base</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>BaseModel</h4>
<hr/>
@Html.ValidationSummary(true, "", new {@class = "text-danger"})
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
@Html.TextBoxFor(x=>x.Id)
<input type="submit" value="Create" class="btn btn-default"/>
</div>
</div>
</div>
if(Model is DerviedOne)
{
Html.RenderPartial("DerviedOneView", Model as DerviedOne);
}
if (Model is DerviedTwo)
{
Html.RenderPartial("DerviedTwoView", Model as DerviedTwo);
}
}
第二种观点:
@model WebApplication.Models.DerviedOne
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>DerviedOne</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
第三种观点:
@model WebApplication.Models.DerviedTwo
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>DerviedTwo</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}