> mvc textboxfor:初始與更新值
>此示例在ASP.NET MVC應用程序中演示了一個常見的問題,其中TextBoxFor
>讓我們檢查MVC操作並查看方案:
控制器操作:
> view:
<code class="language-csharp">[HttpPost] public ActionResult SomeInformation() { var test1 = new DataSites { Latitude = "LATITUDE2" }; return RedirectToAction("Index", test1); } [HttpPost] public ActionResult Index(DataSites dataSiteList) { if (dataSiteList.Latitude != null) { var test = new DataSites { Latitude = "LATITUDE" }; return View(test); } return View(dataSiteList); }</code>
模型:
<code class="language-csharp">@model miniproj2.Models.DataSites <p> @Html.TextBoxFor(x => x.Latitude) </p></code>
>問題:
>在導航至<code class="language-csharp">public class DataSites { public string Latitude { get; set; } }</code>
>時,視圖顯示“ latitude2”,而不是預期的“ latitude” 。 。
/Home/SomeInformation
>說明:Index
>帶有模型將數據傳遞為路由值。 然後使用此值(“ Latitude2”)將默認模型活頁夾填充。 即使操作試圖分配新值(“緯度”),現有>值也優先。
>解決方案:RedirectToAction
ModelState
有效地解決了兩種方法:Index
ModelState
在分配新值之前,
clear ModelState:清除
ModelState
實例,繞過模型完全綁定:Index
<code class="language-csharp">[HttpPost] public ActionResult Index(DataSites dataSiteList) { ModelState.Clear(); // Add this line if (dataSiteList.Latitude != null) { var test = new DataSites { Latitude = "LATITUDE" }; return View(test); } return View(dataSiteList); }</code>
以上是為什麼我的TextBoxfor在MVC中重定向後顯示' Latitude2”而不是' Latitude”?的詳細內容。更多資訊請關注PHP中文網其他相關文章!