我怎样才能在asp.net MVC 3中制作可重用的partialview
我想制作一个带有 2 个下拉列表的部分视图。 DDL 数据必须从数据库生成。我是 MVC 新手。制作此部分视图的正确方法是什么?
谢谢
I want to make a partialview with 2 dropdownlists. DDL data have to generate from db. I am new in MVC. What will be the proper way to make this Partialview?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(假设您使用的是 Visual Studio)
在项目的
Views
文件夹下找到一个名为“Shared”的文件夹(如果不存在则创建它)。右键单击该文件夹,选择“添加->查看”。在“添加视图”对话框中指定视图名称、模型类型(如果您愿意)并设置复选框“创建为局部视图”。模型类型可能应该是一个具有两个List
元素的新模型类。在任何需要使用此视图的地方,请包含标记,
其中 YourModel 与分部视图声明中指定的模型具有相同的类型。
(Assuming you're using Visual Studio)
Under
Views
folder in your project find a folder named "Shared" (or create it if doesn't exist). Right-click this folder, select "Add->View". In the dialog "Add View" specify view name, model type (if you wish) and set the checkbox "Create as a partial view". Model type should probably be a new model class with twoList<string>
elements.Anywhere you need to use this view, include the markup
where YourModel has the same type as a model specified in partial view declaration.
根据我的经验,创建操作并调用
RenderAction()
传递相关参数比使用RenderPartial()
更好。原因是您需要将完全填充的模型传递给 RenderPartial,这意味着您必须在使用此“部分视图”的所有控制器中复制用于填充此模型的代码。我发现创建一个单独的操作可以接收多个参数(即对象的 id)并执行所有必需的步骤来填充模型(即从数据库加载对象)要干净得多。您可以使用
ChildActionOnly
属性标记该新操作,这样就无法直接调用它。From my experience it's better to create action and call
RenderAction()
passing relevant parameters than usingRenderPartial()
. The reason is that you need to pass a fully populated model toRenderPartial
and that means you have to duplicate the code for populating this model in all the controllers that use this 'partial view'.I found it much cleaner to create a separate action that can receive a number of parameters (ie. id of the object) and than perform all the required steps to populate the model (ie. load the object from database). You can mark that new action with
ChildActionOnly
attribute so it cannot be called directly.