我有問題,文本框的值沒有用模型中的新值更新。 @ Html.TextBoxFor(M => m.MvcGridModel.Rows [j]的.ID)如何更新文本框的值@ Html.TextBoxFor(m => m.MvcGridModel.Rows [j] .Id)
首先收集MvcGridModel.Rows得到填充了一些數據,那麼,當按下按鈕並提交獲得新數據成功的形式,但它不會更新文本框的值。
你有什麼想法嗎? 預先感謝您
我有問題,文本框的值沒有用模型中的新值更新。 @ Html.TextBoxFor(M => m.MvcGridModel.Rows [j]的.ID)如何更新文本框的值@ Html.TextBoxFor(m => m.MvcGridModel.Rows [j] .Id)
首先收集MvcGridModel.Rows得到填充了一些數據,那麼,當按下按鈕並提交獲得新數據成功的形式,但它不會更新文本框的值。
你有什麼想法嗎? 預先感謝您
這是因爲TextBoxFor等HTML幫助器在綁定它們的值時只會在ModelState中查找,並且只能在模型中查找。因此,如果在您的POST操作中嘗試修改某些屬於初始POST請求的值,則必須將其從ModelState中移除,以及如果希望這些更改在視圖中生效。
例如:
[HttpPost]
public ActionResult Foo(MyViewModel model)
{
// we change the value that was initially posted
model.MvcGridModel.Rows[0].Id = 56;
// we must also remove it from the ModelState if
// we want this change to be reflected in the view
ModelState.Remove("MvcGridModel.Rows[0].Id");
return View(model);
}
此行爲是故意的,它是由設計。這就是例如允許有以下POST操作:
[HttpPost]
public ActionResult Foo(MyViewModel model)
{
// Notice how we are not passing any model at all to the view
return View();
}
,但在視圖中你得到了用戶在輸入字段最初輸入的值。
還有一個ModelState.Clear();
方法可用於從模型狀態中刪除所有鍵,但要小心,因爲這也會刪除任何關聯的模型狀態錯誤,因此建議您只從您打算修改的ModelState中刪除值POST控制器操作。
所有這一切被說,在一個設計合理的應用程序,你不應該需要這個。因爲你應該使用PRG pattern:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
// there was some error => redisplay the view without any modifications
// so that the user can fix his errors
return View(model);
}
// at this stage we know that the model is valid.
// We could now pass it to the DAL layer for processing.
...
// after the processing completes successfully we redirect to the GET action
// which in turn will fetch the modifications from the DAL layer and render
// the corresponding view with the updated values.
return RedirectToAction("Index");
}
太好了!非常感謝你! :) – 2012-07-05 09:45:30
不客氣。 – 2012-07-05 09:51:29