Basically I get a value from a dropdownlist and pass it to a client method through AJAX. Based on this value, I get data, which I want to put into a textbox.
<script type="text/javascript">
$('#dropdownlist').change(function () {
$.post('/Index/GetJSON/' + this.value, null,
function (data) {
$('#somefield').val(data)
});
});
</script>
So this method gets called:
[HttpPost]
public JsonResult GetJSON(int ID)
{
return Json(data);
}
Markup
@Html.EditorFor(m => m.somefield)
somefield does change it’s value visually. But it does not get updated when I inspect it’s value. It’s as if val(data.ID) doesn’t register to the model. Due to my code, I can’t call ModelState.Clear() either…
The reason I use this approach, and not Ajax.Form and partial views, is because I have all the markup inside a HTML.BeginForm (which is submitted) with many different dropdownlists interacting through textboxes through AJAX, and you cannot nest Ajax.Form with HTML.BeginForm. Thus I cannot submit changes to the model through the Ajax.Form and call ModelState.Clear().
.val()sets the value property of an element if you want the change to be reflected in the elements value attr use.attr()