为什么我的MVC ViewModel成员被ActionResult参数覆盖? [英] Why is my MVC ViewModel member overridden by my ActionResult parameter?

查看:119
本文介绍了为什么我的MVC ViewModel成员被ActionResult参数覆盖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是错误还是功能?

为了简洁和易于复制,下面的所有代码都经过了简化,除了突出显示行为之外,实际上没有做任何有用的事情.

All code below has been simplified for the sake of brevity and easy replication and does not actually do anything useful other than highlight the behavior.

我有一个包含一个名为ID的int的类:

I have a class that includes an int named ID:

public class FooterLink
{
    public int ID { get; set; }
}

在我的控制器中,我有一个编辑"操作结果,该结果带有一个名为"id"的参数:

In my controller, I have an Edit actionresult that takes a parameter called 'id':

public ActionResult Edit(int id)
{
    return View(new FooterLink() { ID = 5 }); //notice that I am explicitly setting the ID value here.
}

在我的索引视图中,有一个指向指定'id'参数的编辑操作的链接:

in my index view I have a link to the edit action that specifies the 'id' parameter:

<%= Html.ActionLink("Edit", "Edit", new { id = 1 })%>

在我看来,我有几个文本框:

In my view I have a couple of text boxes:

<%= Html.TextBox("ID", Model.ID)%>
<%= Html.TextBox("Blah", Model.ID) %>

以HTML呈现以下内容:

which renders the following in HTML:

<input id="ID" name="ID" type="text" value="1">
<input id="Blah" name="Blah" type="text" value="5">

请注意,id为"ID"的输入不是从Model中获取其值,就像我告诉它...而是从提供给ActionResult的参数中获取.这种行为与Html.TextBoxFor,Html.Hidden,Html.HiddenFor等相同.

Notice that the input with an id of "ID" is getting its value not from the Model like I am telling it to...but from the parameter that was supplied to my ActionResult. This behavior is the same with Html.TextBoxFor, Html.Hidden, Html.HiddenFor, etc.

有什么作用?

编辑:我本想很久以前进行更新的,但是从来没有修改过.发生这种情况的原因是因为ModelState在方法中将有一个带有"id"参数值的"id"条目,并且MVC ViewEngine在填充HTML帮助程序而不是Model时首先检查ModelState.要解决此问题,您只需在返回之前在控制器中添加以下行即可:

I meant to update this a long time ago but never got around to it. The reason that this is happening is because the ModelState will have an "id" entry with the value of the "id" parameter in the method and the MVC ViewEngine first checks the ModelState when filling in Html helpers instead of the Model. In order to work around this, you can simply add the following line in your controller just before the return:

ModelState.Remove("id");

现在<%= Html.TextBox("ID",Model.ID)%>将从Model而不是ModelState获取值.问题解决了.

Now the <%= Html.TextBox("ID", Model.ID)%> will get the value from the Model and not the ModelState. Problem solved.

推荐答案

这就是html帮助器的工作方式.他们将首先查看请求url中是否有ID参数,并使用该值代替模型中指定为第二个参数的值.

That's how html helpers work. They will first look if there's ID parameter in the request url and use that value instead of the one specified as second argument in the model.

这篇关于为什么我的MVC ViewModel成员被ActionResult参数覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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