Very simple Controller
public JsonResult A1(Guid? id)
{
var model = new MyModel { Id = g2, Id2 = g2, Name = "A1" };
return new JsonResult
{
Data = new
{
html = this.RenderPartialView("A1", model),
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
public JsonResult A2(Guid? id)
{
ModelState.Clear();
var model = new MyModel { Id = g2, Id2 = g2, Name = "A2" };
return new JsonResult
{
Data = new
{
html = this.RenderPartialView("A1", model),
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
Very simple View with two buttons and script
<p><a class="btn btn-default" href="#" onclick="F1(1)">NO ModelState.Clear()</a></p>
<p><a class="btn btn-default" href="#" onclick="F1(2)">ModelState.Clear()</a></p>
function F1(a) {
$.ajax({
type: 'GET',
url: '@Url.Content("~/Home/A")' + a,
data: {
id: '@ModelBug.Controllers.HomeController.g1'
},
dataType: 'json',
beforeSend: function (xhr) {
},
success: function (data) {
$("#col" + a).append('<div class="row"><div class="col-md-12">' + data.html + '</div></div>');
},
error: function () {
}
});
}
Very simple rendered View
<div>Model.Id = @Model.Id</div>
<div>TextBoxFor(model => model.Id) = @Html.TextBoxFor(model => model.Id)</div>
<div>TextBoxFor(model => Model.Id) = @Html.TextBoxFor(model => Model.Id)</div>
<div></div>
<div>Model.Id2 = @Model.Id2</div>
<div>TextBoxFor(model => model.Id2) = @Html.TextBoxFor(model => model.Id2)</div>
<div>TextBoxFor(model => Model.Id2) = @Html.TextBoxFor(model => Model.Id2)</div>
<div></div>
<div>Model.Name = @Model.Name</div>
<div>TextBoxFor(model => model.Name) = @Html.TextBoxFor(model => model.Name)</div>
<div>TextBoxFor(model => Model.Name) = @Html.TextBoxFor(model => Model.Name)</div>
<div></div>
<div></div>
In result view in TextBoxFor(model => Model.Id) without ModelState.Clear()
show 4a01aadd-c61a-4524-95f6-e88a665c0745 (from param (Guid? id))
must be d2afb9a8-fb43-4237-9f34-abc7e5b59a41** (from public static Guid g2)
Main problem
Why value in TextBoxFor() from param id not from model.Id ?
P.S. This problem get in big project where model get from DataBase but in view model.Id is different from Database, model.Id = param of query.
must be x.Id = d2afb9a8-fb43-4237-9f34-abc7e5b59a41? What are the values of the parameteridandg2. (and why are you returning json instead of a partial view?)id. Its value is added toModelStatewhen the method is called. Your model also has a property namedidwhich you set to a different value. But the html helpers use the values fromModelStateif they exist. You can easily solve this by changing the name of one or the other so they do not match (or useModelState.Clear()as per your 2nd example)ModelStaterather that the value of the model property. Its by design! If you don't want that behavior, then change the name of your method parameter or the name of the model property or useModelState.Clear()