在具有不同模型的多个视图中的MVC PartialView [英] MVC PartialView in multiple Views with different models

查看:96
本文介绍了在具有不同模型的多个视图中的MVC PartialView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,更多地是关于如何做某事的问题,而不是实际的编码问题.

This may be a silly question and is more of a question about how to do something rather than an actual coding issue.

我想要一个局部视图,其中包含一个搜索表单和搜索结果,并使用模型Suppliers.

I want to have a partial view which contains a search form and search results and uses model Suppliers.

然后,该局部视图将在使用不同模型的多个视图中呈现.

This partial view would then be rendered in multiple views that use different models.

这是否对我来说可行,还是我必须在每个视图内创建搜索表单或为每个视图创建局部视图,以便该视图和局部视图使用相同的模型?

Is it possible for me to this or do I have to create the search form within each view or create a partial view for each view so that the view and partial view use the same model?

如果我将Suppliers模型用于部分视图,将另一模型用于视图,则只会出现错误:

If I use the Suppliers model for the partial view and another model for the view I just get error:

传递到词典中的模型项的类型为'x',但是此词典需要类型为'y'的模型项.

The model item passed into the dictionary is of type 'x', but this dictionary requires a model item of type 'y'.

推荐答案

您绝对可以使用不同的实现来做到这一点.

You can definitely do that with different implementations.

第一个选项:

您可以从拥有的共享"视图中删除模型,并使其与从控制器传递到视图的ViewBag或ViewData一起使用.显然,您将需要填充此视图包或查看所有控制器操作中的数据,这些操作将返回此共享的部分视图.

You can drop the Model from the "Shared" view that you have and have it work with a ViewBag or ViewData that you pass to the view from your controllers. Obviously you will need to populate this view bag or view data within all the controller actions that will return this shared partial view.

第二个选项:

您可以在视图模型供应商"中拥有另一个可以使用的属性,而不是将供应商"作为共享视图的视图模型,但是在呈现共享视图时,您需要指定属性并将其传递作为共享视图的模型,例如:

Instead of having Suppliers as the view model of the shared view, you can have another property in the view model "Supplier" that you can use, but when you are rendering the shared view you need to specify the property and pass it as the Model to the shared view like:

Html.RenderPartial("MySharedView", Model.SharedViewModel);

现在,您必须对所有其他呈现此共享的视图执行相同的操作,并且基本上将这些"SharedViewModel"作为这些视图模型中的属性,并将Model.SharedViewModel传递给共享视图.

Now you have to do the same thing for all other views that render this shared and basically have this "SharedViewModel" as a property in those view models and pass the Model.SharedViewModel to the shared view.

请确保还有其他选择,一旦您更熟悉MVC中的共享视图,便可以找到.

For sure there are other options too that you can find out once you get more comfortable with Shared Views in MVC.

这篇关于在具有不同模型的多个视图中的MVC PartialView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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