我必须有一些错误的设置,因为我无法让 UpdateModel 函数根据通过 FormCollection 传入的信息正确更新我的模型。
我的视图看起来像:
@model NSLM.Models.Person
@{
ViewBag.Title = "MVC Example";
}
<h2>My MVC Model</h2>
<fieldset>
<legend>Person</legend>
@using(@Html.BeginForm())
{
<p>ID: @Html.TextBox("ID", Model.ID)</p>
<p>Forename: @Html.TextBox("Forename", Model.Forename)</p>
<p>Surname: @Html.TextBox("Surname", Model.Surname)</p>
<input type="submit" value="Submit" />
}
</fieldset>
我的模型是:
namespace NSLM.Models
{
public class Person
{
public int ID;
public string Forename;
public string Surname;
}
}
我的控制器是:
[HttpPost]
public ActionResult Details(FormCollection collection)
{
try
{
// TODO: Add update logic here
Models.Person m = new Models.Person();
// This doesn't work i.e. the model is not updated with the form values
TryUpdateModel(m);
// This does work
int.TryParse(Request.Form["ID"], out m.ID);
m.Forename = Request.Form["Forename"];
m.Surname = Request.Form["Surname"];
return View(m);
}
catch
{
return View();
}
}
正如您所看到的,如果我手动分配每个属性它工作正常,那么我没有设置什么可以让模型使用表单值更新?
谢谢,
标记