Asp.net mvc 2 ASP.NET MVC2:更新模型以进一步修改POST处理程序。

Asp.net mvc 2 ASP.NET MVC2:更新模型以进一步修改POST处理程序。,asp.net-mvc-2,Asp.net Mvc 2,型号: 控制器: 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 Edi

型号:

控制器:

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");
}
控制器中带有注释的代码不能像我预期的那样工作。如何实现所需的行为?

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

一种可能的解决方法是从modelstate中删除该值:

<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();" />
if (typeChanged)
{
    ModelState.Remove("Value");
    model.Value = 0; // I need to update model here and pass for futher editing
    return View(model);
}