开发者

Asp MVC 3.0 Problem with Ajax form input value

I have cratet simple Model

public class ModelTest
{
    public string My开发者_JS百科Value { 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:

Asp MVC 3.0 Problem with Ajax form input value

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.

Asp MVC 3.0 Problem with Ajax form input value

Why textBox loses value from model?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜