【问题标题】:MVC3 Unobtrusive Ajax - Partial View Not Reflecting ModelMVC3 Unobtrusive Ajax - 部分视图不反映模型
【发布时间】:2012-01-20 22:04:08
【问题描述】:

一切似乎都按预期工作,除了在插入对象后返回带有NAME = "foo" 模型的部分时,它不会使用模型中的值更改名称和百分比文本框。

当我通过验证消息在部分标题中输出@Model.Name 时,它会正确显示"foo"。但是表单仍然会显示提交时文本框中的内容。

HTML

<div id="createBeerForm">
    @{Html.RenderPartial("CreatePartial", new BeerCreateModel());}
</div>

创建部分

@{
    AjaxOptions options = new AjaxOptions
    {
        HttpMethod = "Post",
        UpdateTargetId = "createBeerForm", 
        InsertionMode = InsertionMode.Replace
    };        
}

@using (Ajax.BeginForm("Create", "Beer", null, options, new { @class = "form-stacked" }))
{
    @Html.ValidationSummary(true, "You have errors. Fix them.")
    @Html.LabelFor(m => m.Name)
    <div>
        @Html.TextBoxFor(m => m.Name, new { @class = "xlarge" })  
        @Html.ValidationMessageFor(m => m.Name)
    </div>
    @Html.LabelFor(m => m.PercentAlcohol)
    <div>
        @Html.TextBoxFor(m => m.PercentAlcohol, new { @class = "xlarge" }) 
        @Html.ValidationMessageFor(m => m.PercentAlcohol)
    </div>
    <p>
        <input type="submit" value="Create Beer" />
    </p>
}

控制器

    [HttpPost]
    public ActionResult Create(BeerCreateModel model)
    {
        if (ModelState.IsValid)
        {
            //Add Beer to DB
            return PartialView("CreatePartial", new BeerCreateModel { Name = "foo"});
        }
        else
        {
            return PartialView("CreatePartial", model);
        }
    }

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 model-view-controller unobtrusive-javascript


    【解决方案1】:

    如果您打算更改 POST 控制器操作中的值,则必须清除模型状态。 HTML 助手在绑定时首先查看模型状态,然后查看模型。所以:

    [HttpPost]
    public ActionResult Create(BeerCreateModel model)
    {
        if (ModelState.IsValid)
        {
            //Add Beer to DB
    
            // Here you are modifying the value of the Name parameter
            // in your model. But this parameter is also in ModelState.
            // So if you want this change to reflect on the subsequent view you
            // need to either clear it from the modelstate
            ModelState.Remove("Name");
            return PartialView("CreatePartial", new BeerCreateModel { Name = "foo"});
        }
        else
        {
            return PartialView("CreatePartial", model);
        }
    }
    

    【讨论】:

    • 仅执行 Model.Clear() 有什么副作用吗?这个想法是表单将处于模式中,如果成功,我想加载一个空白并隐藏模式。
    • @Blankasaurus,是的,您正在擦除整个 ModelState 以及任何验证错误。如果你不关心这个,那么你可以做到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 1970-01-01
    • 2012-12-30
    相关资源
    最近更新 更多