ASP.NET MVC2: Update of a model for further modifications in a POST handler.

泄露秘密 提交于 2020-01-05 04:06:12

问题


Model:

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

public enum ItemType { Type1, Type2 }

Controller:

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

And of course View:

<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();" />

The code in controller (with the comment) doesn't work as I expect. How could I achieve the needed behavior?


回答1:


As I wrote here multiple times, that's how HTML helpers work and it is by design: when generating the input they will first look at the POSTed value and only after that use the value from the model. This basically means that changes made to the model in the controller action will be completely ignored.

A possible workaround is to remove the value from the modelstate:

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


来源:https://stackoverflow.com/questions/4216832/asp-net-mvc2-update-of-a-model-for-further-modifications-in-a-post-handler

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!