> 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”)并重定向到
>时,视图显示“ 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中文网其他相关文章!