1

我有问题,文本框值没有用模型中的新值更新。@Html.TextBoxFor(m => m.MvcGridModel.Rows[j].Id)

首先集合 MvcGridModel.Rows 填充了一些数据,然后当按下按钮并提交表单时,它成功获取新数据,但它不会更新文本框的值。

你有什么想法?提前谢谢你

4

1 回答 1

3

这是因为诸如 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();一种方法可用于从模型状态中删除所有键,但要小心,因为这也会删除任何相关的模型状态错误,因此建议仅从模型状态中删除您打算在 POST 控制器操作中修改的值。

话虽如此,在一个设计合理的应用程序中,你不应该需要这个。因为您应该使用PRG 模式

[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-05T09:35:25.123 回答