MVC TextBoxFor: Initial vs. Updated Values
This example demonstrates a common issue in ASP.NET MVC applications where TextBoxFor
displays an unexpected initial value instead of the updated value.
Let's examine an MVC action and view scenario:
Controller Actions:
<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>
View:
<code class="language-csharp">@model miniproj2.Models.DataSites <p> @Html.TextBoxFor(x => x.Latitude) </p></code>
Model:
<code class="language-csharp">public class DataSites { public string Latitude { get; set; } }</code>
The Problem: After navigating to /Home/SomeInformation
(setting Latitude to "LATITUDE2") and redirecting to Index
, the view displays "LATITUDE2" instead of the expected "LATITUDE".
Explanation:
The RedirectToAction
with a model passes data as route values. The default model binder then populates ModelState
with this value ("LATITUDE2"). Even though the Index
action attempts to assign a new value ("LATITUDE"), the existing ModelState
value takes precedence.
Solutions:
Two approaches effectively address this:
ModelState
before assigning the new value in the Index
action:<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>
DataSites
instance directly in the Index
action, bypassing model binding entirely:<code class="language-csharp">[HttpPost] public ActionResult Index(DataSites dataSiteList) { var test = new DataSites { Latitude = "LATITUDE" }; // No reliance on dataSiteList return View(test); }</code>
Choosing between these solutions depends on whether you need to access data from dataSiteList
for other purposes within the Index
action. If not, the second solution (avoiding model binding) is cleaner and more efficient. Otherwise, clearing ModelState
is necessary.
The above is the detailed content of Why Does My TextBoxFor Display 'LATITUDE2' Instead of 'LATITUDE' After a Redirect in MVC?. For more information, please follow other related articles on the PHP Chinese website!