MVC 2视图显示错误的模型信息 [英] MVC 2 View showing wrong model info

查看:127
本文介绍了MVC 2视图显示错误的模型信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MVC 2的一个项目,我有一个观点的一个问题。在控制器我有code:

I'm using MVC 2 for a project and I'm having a problem with a view. In the controller I have the code:

return View(calendarDay);

如果我调试这条线,检查calendarDay它告诉我calendarDay.Id属性等于2。
在视图我有一些code是这样的:

If I debug this line and inspect calendarDay it tells me the calendarDay.Id property is equal to 2. In the view I have some code like this:

<%: Html.HiddenFor(model => model.Id) %>

然而,当结合与Id属性= 2 calendarDay后显示的视图我得到这个在生成的HTML:

However, when the view is shown after binding it to a calendarDay with Id property = 2 I get this on the generated HTML:

<input id="Id" name="Id" type="hidden" value="1">

该值是1,所以当我做TryUpdateModel(calendarDay)它获取ID为1,而不是2,当我去到存储库来获取对象删除它,它崩溃,因为它发现了错误的。
任何人都知道我可能是做错了?

The value is 1, so when I do the TryUpdateModel(calendarDay) it gets the Id property to 1 instead of 2 and when I go to the repository to get the object to delete it, it crashes because it finds the wrong one. Anyone knows what I might be doing wrong?

推荐答案

我怀疑你正试图修改张贴的值(1)在你的控制器动作2​​。这是不可能的,因为这是怎么回事呢HTML佣工工作,它是由设计:他们会先看看张贴的值绑定时和之后,在模型中。因此, HiddenFor 帮手忽略模型的标识,并使用该公司发布的一个。

I suspect that you are trying to modify the POSTed value (which is 1) in your controller action to 2. This is not possible because that's how all HTML helpers work and it is by design: they will first look at the POSTed value when binding and after that in the model. So the HiddenFor helper ignores the Id of your model and uses the one that's posted.

作为一种解决方法你可以:

As a workaround you could:

<input type="hidden" name="Id" value="<%: Model.Id %>" />


正如在评论部分@jfar提出了另一个解决办法是返回视图之前清除后动作模型的状态:


As suggested by @jfar in the comments section another workaround is to clear the model state in the post action before returning the view:

MoselState.Clear();

这篇关于MVC 2视图显示错误的模型信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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