问题
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