【问题标题】:ASP.NET MVC2: Update of a model for further modifications in a POST handler.ASP.NET MVC2:更新模型以在 POST 处理程序中进行进一步修改。
【发布时间】:2013-01-24 00:34:20
【问题描述】:

型号:

public class Model
{
    public ItemType Type { get; set; }
    public int Value { get; set; }
}

public enum ItemType { Type1, Type2 }

控制器:

public ActionResult Edit()
{
    return View(new Model());
}

[HttpPost]
public ActionResult Edit(Model model, bool typeChanged = false)
{
    if (typeChanged)
    {
        model.Value = 0; // I need to update model here and pass for further editing
        return View(model);
    }

    return RedirectToAction("Index");
}

当然还有视图:

<div class="editor-label"><%: Html.LabelFor(model => model.Type) %></div>
<div class="editor-field">
    <%: Html.DropDownListFor(
            model => model.Type,
            Enum.GetNames(typeof(MvcApplication1.Models.ItemType))
                .Select(x => new SelectListItem { Text = x, Value = x }),
            new { @onchange = "$(\'#typeChanged\').val(true); this.form.submit();" }            
        )
    %>
    <%: Html.Hidden("typeChanged") %>
</div>

<div class="editor-label"><%: Html.LabelFor(model => model.Value) %></div>
<div class="editor-field"><%: Html.TextBoxFor(model => model.Value) %></div>

<input type="submit" value="Create" onclick="$('#typeChanged').val(false); this.form.submit();" />

控制器中的代码(带有注释)没有按我的预期工作。我怎样才能实现所需的行为?

【问题讨论】:

    标签: asp.net-mvc-2


    【解决方案1】:

    正如我在这里写的multiple 次,这就是 HTML 助手的工作方式,这是设计使然:在生成输入时,他们将首先查看 POST 的值,然后才使用模型中的值。这基本上意味着在控制器操作中对模型所做的更改将被完全忽略。

    一种可能的解决方法是从模型状态中删除该值:

    if (typeChanged)
    {
        ModelState.Remove("Value");
        model.Value = 0; // I need to update model here and pass for futher editing
        return View(model);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-19
      • 2021-08-13
      • 1970-01-01
      • 2011-04-05
      • 1970-01-01
      • 1970-01-01
      • 2021-09-12
      • 2012-12-16
      相关资源
      最近更新 更多