用户控件相当于MVC3? [英] UserControl equivalent in MVC3?

查看:86
本文介绍了用户控件相当于MVC3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Web窗体我们有用户控件。这些控件有一个code-后面,可以在不同的项目中使用/不依赖于其他事情的解决方案。

On Web Forms we have UserControls. These controls have a code-behind and can be used in different projects/solutions not depending on other things.

我想创建呈现一些控制,并会拥有一些链接,将触发事件的控制。我希望他们不要在我的网站连接,我希望能够在其他网站上使用相同的控制。 什么是MVC中的相同呢?是否有可能在其他地方编译视图与控制器,并使用DLL?

I want to create a control that renders some controls and would have some links that would "trigger an event". I want them not to be attached on my website, I want to be able to use the same "control" on another website. What is the equivalent in MVC? Is it possible to compile a view with a controller and use the DLL elsewhere?

推荐答案

最接近的功能等同的WebForms式可重复使用的用户控件的MVC是HTML帮手。一个HTML帮助是返回一些标记的方法。推荐的方法是实现它们的扩展方法的形式关闭的HtmlHelper 或一个MVC页面的某些其他财产:

The closest functional equivalent to WebForms-style reusable user controls in MVC are html helpers. An html helper is a method that returns some markup. The recommended approach is to implement them in the form of extension methods off HtmlHelper or some other property of an MVC page:

public static IHtmlString MyControl(this HtmlHelper helper, string value) {
    return new HtmlString("<p>" + value + "</p>");
}

您可以直接在此方法添加到你的MVC项目,也可以将其添加到一个单独的类库。该类库需要引用的唯一的事情就是System.Web.Mvc.dll程序的的HtmlHelper 引用(它可能还需要System.Web.dll中,如果您使用更多类型)。

You can add this method to your MVC project directly or you can add it to a seperate class library. The only thing that the class library needs to reference is System.Web.Mvc.dll for the HtmlHelper reference (it might also need System.Web.dll if you use more types).

您通常从视图调用它们像这样(本例使用剃刀语法,在MVC 3的新功能)

You usually call them from your view like so (this example uses the Razor syntax that's new in MVC 3)

@Html.MyControl("my value")

虽然表面HTML辅助发射标记,就像用户控件,有显著的差异。其中最重要的是,MVC的观点不具备的WebForms页面生命周期的概念。这意味着,不像用户控件,HTML辅助在单次通过渲染。有喜欢的初始化,装入不多张相,呈现的WebForms等在这里你可以连接服务器端事件与页面上的其他控件进行交互。

While superficially html helpers emit markup just like User Controls, there are significant differences. The most important one is that MVC views don't have the concept of the WebForms page lifecycle. This means that unlike user controls, html helpers are rendered in a single pass. There are no mulitple phases like Init, Load, Render etc in WebForms where you can hook up server-side events to interact with other controls on the page.

根据具体什么类型的事件你正在谈论有可能是适当的MVC为中心的技术来解决你的任务。你能在你想要做什么提供更多的细节? HTML辅助可以说是相当强大的。例如内置的MVC输入控件像 TextBoxFor 可以连接客户端验证等。

Depending on what specific kinds of events you are talking about there might be appropriate MVC-centric techniques to solve your task. Could you provide more detail on what you want to do? Html helpers can be quite powerful. For example the built in MVC input controls like TextBoxFor can hook up client-side validation etc.

这篇关于用户控件相当于MVC3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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