Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 3 Ajax.BeginForm and Html.TextBoxFor does not reflect changes done on the server

I'm using the Ajax.BeginForm helper in ASP.NET MVC3 to submit a form that replaces itself with new values in the form set on the server. However when I use helpers like Html.TextBoxFor I get the values that was submitted, not the values I inserted into the model on the server.

For example; I set SomeValue to 4 in my action and show it in a textbox. I change the value to 8, hit submit and would expect the value to be changed back to 4 in the textbox, but for some reason it stays 8. But if I output SomeValue without using Html helpers it says 4. Anybody have some clue about what is going on?

My controller:

public ActionResult Index(HomeModel model)
{
    model.SomeValue = 4;
    if (Request.IsAjaxRequest())
        return PartialView(model);
    return View(model);
}
public class HomeModel
{
    public int? SomeValue { get; set; }
}

My View (please not that I have all the needed javascript in my layout page):

<div id="ajaxtest">
@using(Ajax.BeginForm(new AjaxOptions{ InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "ajaxtest", HttpMethod = "Post" })) {
    @Html.TextBoxFor(model => model.SomeValue)
    <input type="submit" value="Update" />
}
</div>
like image 327
Tor-Erik Avatar asked Nov 21 '11 20:11

Tor-Erik


People also ask

What is the difference between Ajax BeginForm and Html BeginForm?

BeginForm() will create a form on the page that submits its values to the server as a synchronous HTTP request, refreshing the entire page in the process. Ajax. BeginForm() creates a form that submits its values using an asynchronous ajax request.

What is@ using Html BeginForm()) in MVC?

The Html. BeginForm extension method is used to generate an HTML Form Tag in ASP.Net MVC Razor.

What is Ajax BeginForm in MVC?

Ajax. BeginForm is the extension method of the ASP.NET MVC Ajax helper class, which is used to submit form data to the server without whole page postback. To work Ajax. BeginForm functionality properly, we need to add the reference of jquery.

What is difference between EditorFor and TextBoxFor in MVC?

TextBoxFor: It will render like text input html element corresponding to specified expression. In simple word it will always render like an input textbox irrespective datatype of the property which is getting bind with the control. EditorFor: This control is bit smart.


2 Answers

you can use

ModelState.Clear() 

in your controller method to make the html helpers use your changed model. Otherwise they use the values from the form submit

Have a look at: Asp.net MVC ModelState.Clear

like image 176
iandayman Avatar answered Oct 21 '22 14:10

iandayman


in your POST method you need to do

ModelState.Clear();

to reflect the changes made after the post

like image 41
Rafay Avatar answered Oct 21 '22 15:10

Rafay