【发布时间】:2015-05-06 10:04:17
【问题描述】:
我的项目中有一个场景,如下所示。
创建具有两个视图的 Person。一种是父视图包含人名,另一种是部分视图包含地址信息。
如果我点击父视图中的提交按钮,我需要读取在地址部分视图中输入的数据并将其传递给 PersonViewModel 对象以用于 POST 操作方法。
我无法通过 POST Action 方法访问 AddressViewModel,得到空值。任何人都可以帮助我如何解决此问题。
提前致谢。
请在下面找到示例代码。
视图模型:
public class PersonViewModel
{
public string FirstName{get;set;}
public string LastName{get;set;}
public AddressViewModel Address{get;set;}
}
public class AddressViewModel
{
public class Address1{get;set;}
public class Address2{get;set;}
}
人员控制器
public ActionResult POST(PersonViewModel model)
{
Person person=new Person();
person.FirstName=model.FirstName;
person.LastName=model.LastName;
if(model.Address!=null)
{
person.Address1=model.Address.Address1;
}
return View("Confirmation");
}
地址控制器:
public ActionResult Address()
{
return View();
}
个人视图:
@model POC.ViewModels.PersonViewModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
</div>
</div>
<div>
@{Html.RenderPartial("~/Views/Shared/_Address.cshtml");}
</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 POC.ViewModels.AddressViewModel
<div class="form-horizontal">
<div class="form-group">
@Html.LabelFor(model => model.Address1, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Address1, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Address1, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Address2, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Address2, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Address2, "", new { @class = "text-danger" })
</div>
</div>
</div>
【问题讨论】:
-
在视图中显示你是如何调用局部的。
-
您需要显示视图。如果它没有绑定它是因为你的视图代码是错误的!
-
@Hanu 风景在哪里?
-
@StephenMuecke,我添加了视图。请查看并建议我。
-
您的部分正在使用
name="Address1"生成控件,但您的模型不包含名称为Address1的属性(只有一个名为Address的属性,它是一个包含名为@987654329 的属性的复杂对象@. 我将很快发布一个答案,提供 2 个选项来解决这个问题。
标签: asp.net asp.net-mvc