加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 创建MVC3剃刀助手,如Helper.BeginForm()

发布时间:2020-12-15 18:42:58 所属栏目:asp.Net 来源:网络整理
导读:我想创建一个帮助器,我可以在括号之间添加内容,就像Helper.BeginForm()一样。我不介意为我的帮手创建一个开始,结束,但是这样做很简单和容易。 基本上我想要做的是在这些标签之间包装内容,以便渲染已经格式化 就像是 @using Html.Section("full","The Ti
我想创建一个帮助器,我可以在括号之间添加内容,就像Helper.BeginForm()一样。我不介意为我的帮手创建一个开始,结束,但是这样做很简单和容易。

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

就像是

@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,“title”是该节的标题。

有没有更好的方式来实现这个,而不是做我正在做的事情?

提前感谢任何帮助。

解决方法

这是完全可能的在MVC中使用像Helper.BeginForm这样的方式,该函数必须返回一个实现IDisposable的对象。

IDisposable interface定义了一个名为Dispose的单一方法,它在对象被垃圾回收之前调用。

在C#中,using关键字有助于限制对象的范围,并在离开范围后立即进行垃圾收集。所以,使用它与IDisposable是自然的。

您将需要实现一个实现IDisposable的Section类。构建时,它必须为您的部分提供打开的标签,并在处理完后将其贴现。例如:

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。

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读