How to update the textbox value @Html.TextBoxFor(m => m.MvcGridModel.Rows[j].Id)

独自空忆成欢 提交于 2019-12-20 04:38:48

问题


I have problem, that the text box value doesn't get updated with the new value in the model. @Html.TextBoxFor(m => m.MvcGridModel.Rows[j].Id)

First the collection MvcGridModel.Rows get populated with some data, then when press button and submit the form it get new data successfully, but it doesn't update the textbox's value.

Do you have any ideas? Thank u in advance


回答1:


That's because HTML helpers such as TextBoxFor first look in the ModelState when binding their values and only after that in the model. So if in your POST action you attempt to modify some value that was part of the initial POST request you will have to remove it from the ModelState as well if you want those changes to take effect in the view.

For example:

[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);
}

This behavior is intentional and it is by design. This is what allows for example to have the following POST action:

[HttpPost]
public ActionResult Foo(MyViewModel model)
{
    // Notice how we are not passing any model at all to the view
    return View();
}

and yet inside the view you get the values that the user initially entered in the input fields.

There's also the ModelState.Clear(); method that you could use to remove all keys from the modelstate but be careful because this also removes any associated modelstate errors, so it is recommended to remove only values from the ModelState that you intend to modify inside your POST controller action.

All this being said, in a properly designed application you should not need this. Because you should use the 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");
}


来源:https://stackoverflow.com/questions/11341545/how-to-update-the-textbox-value-html-textboxform-m-mvcgridmodel-rowsj-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!