ASP.NET MVC2: Model update for further modifications to the POST handler.

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 the controller (with the comment) does not work as I expect. How could I achieve the necessary behavior?

+1
source share
1 answer

As I wrote here several times , how HTML helpers work, and this is by design: when creating input, they will first view 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’s action will be completely ignored.

A possible workaround is to remove the value from the model state:

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

Source: https://habr.com/ru/post/1535361/


All Articles