It takes me quite a long time to figure out what the issue is and how to fix it.
Here is a example to explain the problem. Say you have a view which include a partial view called "RandomNumber", which takes a RandomNumberModel object as model. Each time the page refresh or post back, the RandomNumberModel object will generate a new random number.
public class RandomNumberModel
{
public static int Generate() { return new Random().Next(); }
}
Partial View:
@model RandomNumberMode
<p>
@Html.TextBoxFor(m => RandomNumber.new { autocomplete = "off" })
</p>
It turns out after the postback, the values of all the inputs binding using HtmlHelper class are from ModelState instead of from Model. The value changes in model will not be shown in the rendered view. The solution for this is easy:
1. Using the plain html tag for data display instead of using Html helper
<input type="text" name="RandomNumber" id="RandomNumber" value="@Model.RandomNumber" />
2. Change the code in post back action method to update the model values in ModelState
Here is a example to explain the problem. Say you have a view which include a partial view called "RandomNumber", which takes a RandomNumberModel object as model. Each time the page refresh or post back, the RandomNumberModel object will generate a new random number.
public class RandomNumberModel
{
public static int Generate() { return new Random().Next(); }
}
Partial View:
@model RandomNumberMode
<p>
@Html.TextBoxFor(m => RandomNumber.new { autocomplete = "off" })
</p>
It turns out after the postback, the values of all the inputs binding using HtmlHelper class are from ModelState instead of from Model. The value changes in model will not be shown in the rendered view. The solution for this is easy:
1. Using the plain html tag for data display instead of using Html helper
<input type="text" name="RandomNumber" id="RandomNumber" value="@Model.RandomNumber" />
2. Change the code in post back action method to update the model values in ModelState
ModelState.Remove(
"
RandomNumber"
);
Comments