ASP.NET MVC2:在一个POST处理程序进一步修改模型的更新。 [英] ASP.NET MVC2: Update of a model for further modifications in a POST handler.

查看:88
本文介绍了ASP.NET MVC2:在一个POST处理程序进一步修改模型的更新。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

型号:

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

我期望在控制器中的code(带注释)不起作用。我怎么能实现所需的行为?

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

推荐答案

当我写到这里的multiple倍,这是HTML佣工是如何工作的,这是由设计:产生输入时,他们会先看看张贴的价值,只有在使用从模型的价值。这基本上意味着,在控制器动作对模型所做的更改将被完全忽略。

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.

一个可能的解决方法是删除从ModelState中值:

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

这篇关于ASP.NET MVC2:在一个POST处理程序进一步修改模型的更新。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆