创建像 Helper.BeginForm() 这样的 MVC3 Razor Helper [英] Creating MVC3 Razor Helper like Helper.BeginForm()

查看:20
本文介绍了创建像 Helper.BeginForm() 这样的 MVC3 Razor Helper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个助手,我可以像 Helper.BeginForm() 那样在括号之间添加内容.我不介意为我的助手创建一个开始,结束,但这样做非常简单和容易.

I want to create a helper that i can add content between the brackets just like Helper.BeginForm() does. I wouldnt mind create a Begin, End for my helper but it's pretty simple and easy to do it that way.

基本上我想要做的是在这些标签之间包装内容,以便它们呈现已经格式化

basically what i am trying to do is wrapping content between these tags so they are rendered already formatted

类似的东西

@using Html.Section("full", "The Title")
{
This is the content for this section
<p>More content</p>
@Html.TextFor("text","label")
etc etc etc
}

参数full"是该 div 的 css id,the title"是该部分的标题.

the parameters "full" is the css id for that div and "the title" is the title of the section.

除了做我想做的事情之外,还有没有更好的方法来实现这一目标?

Is there a better way to achieve this other than doing what i am trying to do?

在此先感谢您的帮助.

推荐答案

完全有可能.在 MVC 中使用 Helper.BeginForm 之类的方法是,该函数必须返回一个实现 IDisposable 的对象.

It's totally possible. The way this is done in MVC with things like Helper.BeginForm is that the function must return an object that implements IDisposable.

IDisposable 接口定义了一个名为Dispose 在对象被垃圾收集之前调用.

The IDisposable interface defines a single method called Dispose which is called just before the object is garbage-collected.

在 C# 中,using 关键字有助于限制对象的作用域,并在它离开作用域时立即对其进行垃圾回收.因此,将它与 IDisposable 一起使用是很自然的.

In C#, the using keyword is helpful to restrict the scope of an object, and to garbage-collect it as soon as it leaves scope. So, using it with IDisposable is natural.

您需要实现一个实现 IDisposableSection 类.它必须在构建时为您的部分呈现打开标签,并在处理时呈现关闭标签.例如:

You'll want to implement a Section class which implements IDisposable. It will have to render the open tag for your section when it is constructed, and render the close tag when it is disposed. For example:

public class MySection : IDisposable {
    protected HtmlHelper _helper;

    public MySection(HtmlHelper helper, string className, string title) {
        _helper = helper;
        _helper.ViewContext.Writer.Write(
            "<div class="" + className + "" title="" + title + "">"
        );
    }

    public void Dispose() {
        _helper.ViewContext.Writer.Write("</div>");
    }
}

既然类型可用,您可以扩展 HtmlHelper.

Now that the type is available, you can extend the HtmlHelper.

public static MySection BeginSection(this HtmlHelper self, string className, string title) {
    return new MySection(self, className, title);
}

这篇关于创建像 Helper.BeginForm() 这样的 MVC3 Razor Helper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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