简体   繁体   English

MVC 2视图显示错误的模型信息

[英]MVC 2 View showing wrong model info

I'm using MVC 2 for a project and I'm having a problem with a view. 我正在为项目使用MVC 2,但视图存在问题。 In the controller I have the code: 在控制器中,我有以下代码:

return View(calendarDay);

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: 如果我调试此行并检查calendarDay,它将告诉我calendarDay.Id属性等于2。在视图中,我有类似以下代码:

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

However, when the view is shown after binding it to a calendarDay with Id property = 2 I get this on the generated HTML: 但是,在将视图绑定到具有id属性= 2的calendarDay后显示视图时,将在生成的HTML上获取该视图:

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

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. 该值为1,所以当我执行TryUpdateModel(calendarDay)时,它会将Id属性设置为1而不是2;当我进入存储库以删除该对象时,它会崩溃,因为它找到了错误的对象。 Anyone knows what I might be doing wrong? 有人知道我可能做错了吗?

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. 我怀疑您正在尝试将控制器操作中的POSTed值(即1)修改为2。这是不可能的,因为这是所有HTML帮助器的工作方式,它是有意设计的:绑定时,他们将首先查看POSTed值。然后在模型中 So the HiddenFor helper ignores the Id of your model and uses the one that's posted. 因此, HiddenFor帮助程序将忽略模型的ID,并使用发布的ID。

As a workaround you could: 解决方法是:

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

As suggested by @jfar in the comments section another workaround is to clear the model state in the post action before returning the view: 如@jfar在注释部分所建议的,另一种解决方法是在返回视图之前在post操作中清除模型状态:

MoselState.Clear();

Seems like the problem is that the view is using the id from the controller and not the one from the model. 似乎问题在于视图使用的是控制器的ID,而不是模型的ID。 I just changed the parameter name and works fine now. 我刚刚更改了参数名称,现在可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM