在我的控制器在Asp.net MVC 1應用程序中,我想使用UpdateModel在我的控制器中使用POST數據填充變量。我已經看了幾十個例子,但即使是最基本的例子也似乎對我無言以對。Asp.net MVC UpdateModel(myClass)的基本問題
這是一個非常基本的例子,它只是不起作用。 我在做什麼錯?
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 Framework的第374頁上的示例爲基礎,它不使用[AcceptVerbs(HttpVerbs.Post)]頭或類型化參數。這本書不正確嗎? – Glenn 2009-09-01 16:14:33
想通了。這本書是正確的。它忽略了在這種情況下,UpdateModel所使用的反射方法僅適用於屬性,即使通過可能適用於它當前沒有的字段。看起來像一個MVC錯誤給我。屬性通常是更好的練習,但對於簡單的視圖模型,它更容易設置頂部的默認值,而不是重新輸入所有屬性值,並在類構造函數中設置默認值。 – Glenn 2009-09-01 16:32:31