ASP.NET MVC,强类型视图,部分视图参数故障 [英] ASP.NET MVC, strongly typed views, partial view parameters glitch

查看:19
本文介绍了ASP.NET MVC,强类型视图,部分视图参数故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我得到了继承自的视图:

If i got view which inherits from:

System.Web.Mvc.ViewPage<Foo>

其中 Foo 有一个类型为字符串的属性 Bar
并且视图想要呈现继承自的强类型部分视图:

Where Foo has a property Bar with a type string
And view wants to render strongly typed partial view which inherits from:

System.Web.Mvc.ViewUserControl<string>  

像这样:

Html.RenderPartial("_Bar", Model.Bar);%>

那为什么会抛出这个:

传入字典的模型项的类型是'Foo'
但是这本词典需要一个System.String"类型的模型项.

The model item passed into the dictionary is of type 'Foo'
but this dictionary requires a model item of type 'System.String'.

bar 未初始化时?

when bar is not initialized?

更具体的:为什么它传递 Foo,它应该传递 null 的地方?

More specific: why it passes Foo, where it should pass null?

推荐答案

正如@Dennis 指出的,如果模型值为空,它将使用视图中的现有模型.这样做的原因是支持使用仅包含局部视图名称的签名调用局部视图并使其重用现有模型的能力.在内部,所有 RenderPartial 助手都遵循单个 RenderPartialInternal 方法.使用该方法重用现有模型的方法是为模型传入一个空值(仅采用视图名称的签名就是这样做的).当您将空值传递给包含视图名称和模型对象的签名时,您实际上是在复制仅采用视图名称的方法的行为.

As @Dennis points out, if the model value is null, it will use the existing model from the view. The reason for this is to support the ability to call a partial view using a signature that contains only the partial view name and have it reuse the existing model. Internally, all of the RenderPartial helpers defer to a single RenderPartialInternal method. The way you get that method to reuse the existing model is to pass in a null value for the model (which the signature that takes only a view name does). When you pass a null value to the signature containing both a view name and a model object, you are essentially replicating the behavior of the method that takes only the view name.

这应该可以解决您的问题:

This should fix your issue:

<% Html.RenderPartial( "_Bar", Model.Bar ?? string.Empty ) %>

这篇关于ASP.NET MVC,强类型视图,部分视图参数故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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