为什么使用我的路由数据我textBoxFor? [英] Why is my textBoxFor using my route data?

查看:102
本文介绍了为什么使用我的路由数据我textBoxFor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有以下三行:

<div style="background-color: lightgreen;">@Html.TextBoxFor(m => m.Id)</div>
<div style="background-color: green;">@Html.DisplayTextFor(m => m.Id)</div>
<div style="background-color: pink;">@Model.Id</div>

我已经确定了的浅绿值不是我Model.Id而是由我的路线设置ID:

I've identified that the lightgreen value is not my Model.Id but the Id that is set by my route:

routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "MyFunController", action = "Index", id = UrlParameter.Optional });

我来这里翻过一些说明:

I've come accross some explanations here:

  • http://forums.asp.net/t/1792086.aspx/1
  • http://www.hanselman.com/blog/TheWeeklySourceCode38ASPNETMVCBetaObscurityModelStateIsValidIsFalseBecauseModelBinderPullsValuesFromRouteData.aspx
  • http://ayende.com/blog/3683/reproducing-a-bug

但他们都离开了我对我的胃口。我在寻找一个聪明的办法来解决这个问题,我不想改变我的模型的属性名称也不想改变路线项目的名称。如果我这样做会重新present了很多工作,对我来说,是不理想的。

But they have all left me on my appetite. I'm looking for a smart way to work around this, I don't want to change my model's property names nor do I want to change the name of the route item. If I do it will represent a lot of work for me and is not ideal.

我敢肯定我不是唯一一个有这个问题?

I'm sure I'm not the only one with this issue?

(这是MVC 4)

谢谢!

推荐答案

您可以删除有问题的值的ModelState (这是在HTML佣工使其从)在控制器的动作正在呈现的观点:

You could remove the problematic value from the ModelState (which is where the Html helpers are taking it from) in the controller action that is rendering the view:

public ActionResult SomeAction(int id)
{
    ModelState.Remove("Id");
    MyViewModel model = ...
    return View(model);
}

现在它是要去习惯的文本框,并从路线不是有人来您的视图模型的编号属性。

Now it's the Id property of your view model that's gonna get used by the TextBox and not the one coming from the route.

显然,这只是一个丑陋可怕的解决方法。正确的方法是当然正确定义您的视图模型,这样你就没有这样的命名冲突。

Obviously that's only an ugly horrible workaround. The correct way is to of course properly define your view models so that you do not have such naming collisions.

这篇关于为什么使用我的路由数据我textBoxFor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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