[英]ASP.NET MVC PartialView generic ModelView
I have an ASP.NET MVC application which I want to dynamically pick the partial view and what data gets passed to it, while maintaining strong types. 我有一个ASP.NET MVC应用程序,我想动态选择部分视图以及将哪些数据传递给它,同时保持强类型。
So, in the main form, I want a class that has a view model that contains a generically typed property which should contain the data for the partial view's view model. 因此,在主要形式中,我想要一个具有视图模型的类,该视图模型包含一个通用类型的属性,该属性应包含部分视图的视图模型的数据。
public class MainViewModel<T>
{
public T PartialViewsViewModel { get; set; }
}
In the User Control, I would like something like: 在用户控件中,我想要以下内容:
Inherits="System.Web.Mvc.ViewUserControl<MainViewModel<ParticularViewModel>>" %>
Though in my parent form, I must put 虽然以我父母的形式,我必须把
Inherits="System.Web.Mvc.ViewPage<MainViewModel<ParticularViewModel>>" %>
for it to work. 为它工作。
Is there a way to work around this? 有办法解决这个问题吗? The use case is to make the user control pluggable.
用例是使用户控件可插入。 I understand that I could inherit a base class, but that would put me back to having something like a dictionary instead of a typed view model.
我知道我可以继承基类,但是那会让我回到拥有字典之类的东西,而不是类型化的视图模型。
You can use the DisplayTemplates and EditorTemplates to accomplish this. 您可以使用DisplayTemplates和EditorTemplates完成此操作。 So if I'm reading your question right, you have a setup like this:
因此,如果我没看错您的问题,那么您将具有以下设置:
If you are using .NET 4.0 (yay for covariant generics!) 如果您使用的是.NET 4.0(对于协变泛型,则是这样!)
System.Web.Mvc.ViewPage<MainViewModel<object>>
If you are using .NET 3.5: 如果您使用的是.NET 3.5:
System.Web.Mvc.ViewPage<MainViewModel<object>>
public class MainViewModel
{
public object PartialViewsViewModel { get; set; }
}
You can then invoke DisplayFor on that object to get a partial view. 然后,您可以在该对象上调用DisplayFor以获得局部视图。 So invoking:
因此,调用:
<%= Html.DisplayFor(m => m.PartialViewsViewModel) %>
Will look for a template in your DisplayTemplates folder for a skin of the name of your type. 将在您的DisplayTemplates文件夹中查找您类型名称的外观的模板。 So if you have a ParticularViewModel.ascx in your DisplayTemplates, it will use that control as the 'partial view'.
因此,如果您的DisplayTemplates中有ParticularViewModel.ascx,它将使用该控件作为“局部视图”。 If you were using some other kind of view model type, then search for OtherViewModel.ascx (for example).
如果您使用的是其他类型的视图模型类型,请搜索OtherViewModel.ascx(例如)。
The template for ParticularViewModel.ascx would then have: 然后,ParticularViewModel.ascx的模板将具有:
System.Web.Mvc.ViewUserControl<ParticularViewModel>
Which lets you treat the object as a strongly typed model. 这使您可以将对象视为强类型模型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.