HiddenFor(x => x.Id) is being populated by the UrlParameter instead of the ViewModel

时光怂恿深爱的人放手 提交于 2019-11-26 21:37:34

问题


public ActionResult SomeAction(int Id){
    //Id is set to 2

    var model = //get some thing from db using Id(2);
    //Now model.Id is set to 9;

    return View(model);
}

----------View----------
@Html.HiddenFor(x => x.Id)

When I view source this hidden field is set to 2 not 9. How do I get it to map to the model instead of mapping to the URL routing info?

P.S. I'd prefer not to rename parameters because then I lose my nice looking url's unless i change the routing info. I have done that and it does work, but not what I want.


回答1:


When an Action gets called the framework builds a ModelStateCollection based on the query-string values, post-data, routing values etc. And this ModelStateCollection will be passed to the View. All the HTML input helpers try to the get the values from the ModelStateCollection first, before trying to get the values from the actual model.

Because your input model is the int id but the output model is some new model the helpers will use the values from the ModelStateCollection (from the query string) because the propery names Id are match.

To make it work you have to manually clear the ModelStateCollection before returning the new model to the view:

public ActionResult SomeAction(int Id){
    //Id is set to 2

    ModelState.Clear();

    var model = //get some thing from db using Id(2);
    //Now model.Id is set to 9;

    return View(model);
}



回答2:


You could try this below

<input id="Id" type="hidden" value="@Model.Id" />

May not be exactly what you want but essentially does the same thing.




回答3:


You can use TextBoxFor and make it hidden using CSS as

@Html.TextBoxFor(x => x.Id, new { @style="visibility:hidden; width:4px;"})

It worked for me.



来源:https://stackoverflow.com/questions/8748940/hiddenforx-x-id-is-being-populated-by-the-urlparameter-instead-of-the-viewm

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