我有一个域模型和一个 View 模型,如下所示:
域模型:
namespace MvcApplication1.Models
{
public enum Sex { Male, Female };
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
[Required(ErrorMessage="Please select either Female or Male.")]
public Sex? Sex { get; set; }
}
}
查看模型:
namespace MvcApplication1.ViewModels
{
public class HomeCreateVM
{
public HomeCreateVM()
{
}
public HomeCreateVM(Person p)
{
Person = p;
SelectList = p.Sex.GetSelectList();
}
public Person Person { get; set; }
public SelectList SelectList { get; set; }
}
}
辅助扩展方法定义如下:
namespace MvcApplication1.Models
{
public static class Utilities
{
public static SelectList GetSelectList<XXX>(this XXX? obj) where XXX : struct
{
var values = from XXX x in Enum.GetValues(typeof(XXX))
select new { Text = x.ToString(), Value = x };
return new SelectList(values, "Value", "Text", obj);
}
}
}
Controller :
public ActionResult Create()
{
var p = new Person();
return View(new HomeCreateVM(p));
}
[HttpPost]
public ActionResult Create(Person hc)// the source of problem!
{
if (ModelState.IsValid)//always false!
{
TempData["status"] = hc;
return RedirectToAction("Confirm");
}
else
return View(new HomeCreateVM(hc));
}
HomeCreateVM.cshtml:
@model MvcApplication1.ViewModels.HomeCreateVM
<div>
Name: @Html.EditorFor(model => model.Person.Name)</div>
<div>
Sex: @Html.DropDownListFor(model => model.Person.Sex, Model.SelectList, "--Select--")</div>
创建 View :
@model MvcApplication1.ViewModels.HomeCreateVM
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>HomeCreateVM</legend>
@Html.EditorForModel()
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
问题:
如果 POST Create 操作方法接受 HomeCreateVM
对象作为参数,则没有问题。
但是,如果我将 POST Create 操作方法参数从 HomeCreateVM
更改为 Person
(如上面的代码所示),ModelState.IsValid
始终返回假
。
问题是:“是否可以将 ViewModel 对象传递给 Create View ,但只接受来自 POST Create 操作方法的 DomainModel 对象?”
最佳答案
因为您的 View 是强类型化到 View 模型的,所以您的表单字段将如下所示:
<input type="text" name="Person.Name" />
如果你想正确绑定(bind),你需要指定前缀:
[HttpPost]
public ActionResult Create([Bind(Prefix = "Person")]Person hc)
{
...
}
关于asp.net-mvc - 是否可以将封装 Person 的 ViewModel 对象传递给 Create View ,但仅从 POST Create 操作方法接收 Person 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4912821/