0
votes

I have cratet simple Model

public class ModelTest
{
    public string MyValue { get; set; }
}

With simple controller

public class ModelTestController : Controller
{
    public ActionResult Editor()
    {
        return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Editor(ModelTest modelTest)
    {
        modelTest.MyValue += " Post!";
        return View(modelTest);
    }

    public ActionResult Start()
    {
        return View(new ModelTest { MyValue = "initial value" });
    }
}

With view for Start

<body>
    <h1>testing</h1>
    <div id="editorDiv">
        <% Html.RenderPartial("Editor", Model); %>      
    </div>
</body>

And control Editor:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcTest.Models.ModelTest>" %>

<% using (Ajax.BeginForm("Editor", new AjaxOptions { UpdateTargetId = "editorDiv", })) { %> 
    Current real Value:  <%: Model.MyValue %> <br />

    <%: Html.TextBoxFor(model => model.MyValue) %>  <br />

    <input type="submit" value="Zapisz" id="saveInput" />    
<% } %>

EDIT: (I had little time and I wrote a little understandable)

I'm have initialValue in textbox from model:

enter image description here

Then I wrote text 'Test' into it and press 'Zapisz' button. In my controller post method 'Editor' value should be changed from 'Test' to 'Test Post!' and in view textbox (input) shold have value 'Test Post!'. Instead from Html.TextBoxFor(model => model.MyValue) I get old value 'Test' but from <%: Model.MyValue %> I get current value.

enter image description here

Why textBox loses value from model?

1
Hmmm, I don't understand your problem.Kenji Kina

1 Answers

1
votes

You need to remove the old value from ModelState if you intend to modify a POSTed value inside your controller action that handles the form submission:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Editor(ModelTest modelTest)
{
    ModelState.Remove("MyValue");
    modelTest.MyValue += " Post!";
    return View(modelTest);
}

The reason for this is because standard HTML helpers such as TextBoxFor first look for values present in the ModelState (POST, GET requests values) and if they find the value there they will use it. Only if there is no value with the given name (the one you use in he lambda expression when you construct the helper) they will use the value present in your model.

Note that this behavior is by design and it doesn't matter whether you are doing a normal or AJAX request. So, either remove the value from model state as I showed or write your own helper that will generate a textbox and that will use the value from the model.