Asp.net-Mvc
HiddenFor(x => x.Id) 由 UrlParameter 而不是 ViewModel 填充
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)當我查看原始碼時,此隱藏欄位設置為 2 而不是 9。如何讓它映射到模型而不是映射到 URL 路由資訊?
PS 我不希望重命名參數,因為除非我更改路由資訊,否則我會失去漂亮的 url。我已經做到了,它確實有效,但不是我想要的。
當一個被呼叫時,框架會根據查詢字元串值、post-data、路由值等
Action建構一個。這將被傳遞給. 在嘗試從實際模型中獲取值之前, 所有 HTML 輸入助手都嘗試從first獲取值。ModelStateCollection``ModelStateCollection``View``ModelStateCollection因為您的輸入模型是
int id但輸出模型是一些新模型,所以助手將使用來自ModelStateCollection(來自查詢字元串)的值,因為屬性名稱Id是匹配的。要使其工作,您必須
ModelStateCollection在將新模型返回到視圖之前手動清除: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); }