ASP.NET MVC - the value set on the field does not correspond to the value in the Model - what’s wrong?

While developing our brand new LiveChat called ””, I noticed interesting behaviour, what I never noticed before. In the functions like @Html.EditorFor, @Html.TextBoxFor … or @Html.TextArea, @Html.TextBox … When you do AJAX “postback” of your form like this:

			@using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "FormAjaxContainer" }))
				<div id="FormAjaxContainer">

					<div class="form-group">
						@Html.LabelFor(model => model.WidgetThemeColor, htmlAttributes: new { @class = "control-label col-md-2" })
						<div class="col-md-10">
							@Html.ValidationMessageFor(model => model.WidgetThemeColor, "", new { @class = "text-danger" })
							<div class="input-group BGColorPicker">
								<span class="input-group-addon"><i></i></span>
								@Html.EditorFor(model => model.WidgetThemeColor, new { htmlAttributes = new { @class = "form-control" } })


with value “A” on property WidgetThemeColor and on the server you change the value to value “B” you still see on the input field the value “A”. Its caused by interesting behaviour of the helper function of all controls like @Html.EditorFor, @Html.TextBox …
They first use the value of the POST request and after that the value in the model. This means that even if you modify the value of the model in your controller action if there is the same variable in the POST request your modification will be ignored and the POSTed value will be used. When you want to apply your new value from controller, you need to do this:

Or for particular property by this statement :

And the POSTed value will be ignored while rendering of the View or PartialView.

Comments are closed