ASP>实现MVC可重复使用的谐音 [英] ASP>net MVC reusable partials

查看:106
本文介绍了ASP>实现MVC可重复使用的谐音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经在这两个的WinForms .NET和ASP.net工作了几年,我现在开始进入MVC(有点晚了,我知道)。对我来说一个主要的困惑是可重复使用的部件的概念,类似于web表单UserControl的概念。

Having worked with .net in both winforms and ASP.net for a few years I am now starting to get into MVC (a little late I know). One major confusion for me is the concept of reusable 'components', similar to the concept of a usercontrol in webforms.

例如,我想有一些我的网站,其中一个成员区域内的小部件的是登录用户的详细信息,客户经理。然而,当页面加载数据需要传递作为视图模型/视图数据的一部分,我可以创建此作为部分。我想在多个不同的部分来使用这个小工具,然后这将意味着我需要把code在传递数据到多个不同的控制器。这似乎违反了DRY原则,还是我失去了一些东西?我会像理想的一切,在其中可以在任意一个页面中使用了1分进行封装。

For example, I would like to have a number of 'widgets' within the members area of my site, one of which is the details of the logged in users account manager. I can create this as a partial however when the page loads the data needs to be passed in as part of the ViewModel / View Data. I would like to use this widget in a number of different sections which would then mean that I need to put the code to pass the data in into a number of different controllers. This seems to violate the DRY principle, or am I missing something here? I would ideally like everything to be encapsulated within the 1 partial which can then be used in any page.

推荐答案

您可以通过三种方式:

1)对于没有太多逻辑简单的控制,你可以创建控件的自定义视图模型的新实例:
Html.RenderPartial(YourControl,新YourControlViewModel(){参数1 =值1,参数2 = Model.AnotherValue});

1) For simple controls without much logic, you can create new instance of the custom view model for the control: Html.RenderPartial("YourControl", new YourControlViewModel () { Param1="value1", Param2 = Model.AnotherValue });

2)如果你需要一些后端逻辑控制,可以使用
Html.RenderAction(ActionName,SomeControllerName,RouteValues​​Dictionary);
它会调用标准的控制器动作,使用视图,然后将结果输出回页面。可以[ChildActionOnly]属性附加伤害添加到控制器的方法,以确保该方法将只能从Html.RenderPartial。这是稍微违反MVC原则(视图不能调用控制器),但它非常适合小部件,它在Ruby on Rails的世界中使用没有太大的问题。您可以从 Haacked

2) If you need some back end logic for the control, you can use Html.RenderAction("ActionName", "SomeControllerName", RouteValuesDictionary); It will call standard controller action, use the view, and insert the resulting output back to the page. You can add [ChildActionOnly] atribute to the controller method to ensure that the method will be available only from the Html.RenderPartial. It is slightly violating the MVC principle (view shouldn't call controller), but its great for widgets, and it is used in the Ruby on Rails world without much issues. You can check great article from Haacked

3)创建,如自定义日期格式的任务,计算自定义HTML帮助等。

3) Create custom html helper for tasks like custom date formatting, calculating etc..

在你的情况,我会选择第二。

In your case, I would choose the number two.

这篇关于ASP>实现MVC可重复使用的谐音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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