Asp MVC 3.0 Ajax表单输入值问题

时间:2011-07-15 15:38:19

标签: c# asp.net ajax asp.net-mvc-3

我有简单的模型

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

使用简单的控制器

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" });
    }
}

查看开始

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

控制编辑:

<%@ 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" />    
<% } %>
编辑:(我没有时间,我写了一点可以理解)

我在模板文本框中有initialValue:

enter image description here

然后我在其中输入文本'Test'并按'Zapisz'按钮。在我的控制器post方法'Editor'值应该从'Test'更改为'Test Post!'并且在视图中文本框(输入)shold具有值'Test Post!'。取而代之的是Html.TextBoxFor(model =&gt; model.MyValue),我得到旧值'Test'但是来自&lt;%:Model.MyValue%&gt;我得到了当前的价值。

enter image description here

为什么textBox会从模型中丢失价值?

1 个答案:

答案 0 :(得分:1)

如果您打算修改处理表单提交的控制器操作中的POSTed值,则需要从ModelState中删除旧值:

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

之所以这样,是因为标准的HTML帮助程序(如TextBoxFor)首先查找ModelState中存在的值(POST,GET请求值),如果找到值,则会使用它。只有当没有给定名称的值(在构造帮助器时在lambda表达式中使用的值)时,它们才会使用模型中存在的值。

请注意,此行为是设计使然,无论您是执行普通请求还是AJAX请求都无关紧要。因此,要么在我展示时从模型状态中删除值,要么编写自己的帮助程序,生成文本框并使用模型中的值。

相关问题