我有一个复杂的模型
public class Person
{
public int Id{get;set;}
public string Name{get; set;}
public virtual Address Address { get; set; }
}
public class Address
{
public int Id{get; set;}
public string State{get; set;}
}
在我的编辑视图中,我显示了Address.State
@Html.EditorFor(model => model.Address.State)
我的帖子操作方法看起来像
public ActionResult Edit(Person person)
{
var state = person.Address.State;
return view();
}
但地址是null
。
使用像这样的复杂模型的正确方法是什么?
答案 0 :(得分:3)
这是解决方案 -
我使用了你的模型 -
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public int Id { get; set; }
public string State { get; set; }
}
然后呈现Edit视图的Controller动作如下 -
public ActionResult Index()
{
Person p = new Person();
p.Name = "Rami";
p.Address = new Address();
p.Address.State = "California";
return View(p);
}
编辑视图如下 -
@model MVC.Controllers.Person
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm("Submit","Person",FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.Id)
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
@Html.LabelFor(model => model.Address.State, new { @class = "control-label col-md-2" })
@Html.EditorFor(model => model.Address.State)
@Html.ValidationMessageFor(model => model.Address.State)
<input type="submit" value="Save" />
}
最后,当您单击“提交”按钮时,它将点击以下控制器操作 -
public ActionResult Submit(Person p)
{
// Do something with Person p
return null;
}
当您设置断点时,您将获得新值,如下所示 -