【发布时间】:2009-09-01 15:29:50
【问题描述】:
在 Asp.net MVC 1 应用程序的控制器中,我想使用 UpdateModel 在控制器中使用 POST 数据填充变量。我看过几十个例子,但即使是最基本的例子对我来说似乎也无声无息地失败了。
这是一个非常基本的示例,但它不起作用。 我做错了什么?
public class TestInfo
{
public string username;
public string email;
}
public class AdminController : Controller
{
public ActionResult TestSubmit()
{
var test = new TestInfo();
UpdateModel(test);//all the properties are still null after this executes
//TryUpdateModel(test); //this returns true but fields / properties all null
return Json(test);
}
}
//Form Code that generates the POST data
<form action="/Admin/TestSubmit" method="post">
<div>
<fieldset>
<legend>Account Information</legend>
<p>
<label for="username">Username:</label>
<input id="username" name="username" type="text" value="" />
</p>
<p>
<label for="email">Email:</label>
<input id="email" name="email" type="text" value="" />
</p>
<p>
<input type="submit" value="Login" />
</p>
</fieldset>
</div>
</form>
【问题讨论】:
-
感谢大家的快速回复。我喜欢吃完午饭回来看到 4 个答案。我现在正在测试它们。快速旁注。我以史蒂夫·桑德森(Steve Sanderson)的 Pro Asp.net MVC 框架第 374 页为例,它不使用 [AcceptVerbs(HttpVerbs.Post)] 标头或类型化参数。书错了吗?
-
想通了。书是对的。它只是忽略了提及,在这种情况下,UpdateModel 使用的反射方法仅适用于 Properties,即使它可能适用于当前不适用的字段。对我来说似乎是一个 MVC 错误。属性通常是更好的做法,但对于简单的视图模型,它更容易设置字段的默认值,而不是重新键入所有属性值并在类构造函数中设置默认值。
标签: asp.net-mvc binding controller updatemodel