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

问题

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值