MVC 3剃须刀,具有自定义标记/条助手 [英] MVC 3 Razor, Helpers with custom markup/section

查看:163
本文介绍了MVC 3剃须刀,具有自定义标记/条助手的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我甚至不知道这是可能的,但我想我会检查,看看是否有什么办法可以使它更容易些。

I'm not even sure if this is possible, but I thought I would check to see if there is any way to make this easier.

首先,我有一个看起来在我的网站一些重复类似这样的标记:

First, I have some repeated markup in my site that looks like this:

<div class="module">
    <h3>Title</h3>
    <div>
        <p>Information goes here</p>
    </div>
</div>

我想要做的是某种帮手/条的包装这件事,这样我可以做这样的事情。

What I want to do is wrap this up in some kind of helper/section so that I could do something like this

@MyHelper("This is my Title") {
    <p>Here is my custom markup</p>
}

然后,当它呈现,它会注入之间通过参数传入的标题&LT; H3&GT;&LT; / H3&GT; ,并在申报单的自定义标记。自定义标记可以是任何从测试,以形成控制,以一局部视图。这东西是可能的吗?

Then, when it renders, it would inject the title passed in through the parameter between the <h3></h3> and the custom markup in the divs. The custom markup could be anything from test, to form controls, to a partial view. Is this something that is possible?

推荐答案

那么,这里的做一些接近它,使用HTML帮助扩展的一个标准的方式。一个非常简单的版本是什么 Html.BeginForm()一样。

Well, here's a "standard" way of doing something close to it, using an HTML helper extension. A very simple version of what Html.BeginForm() does.

办法:只返回了IDisposable,并让使用语句把剩下的工作

Approach: Simply return an IDisposable, and let the using statement take care of the rest.

这仅仅是概念的一个例子(尽管它的工作原理)。不打算立即重用。很快写有很多快捷键,不是生产code,大量的改进和优化的机会,可能有愚蠢的错误,可以使用TagBuilder等等等等,也可以很容易地进行修改,以重复使用不同的包装材料...包装类(甚至有可能是一个通用1已在ASP.NET MVC - 还没有必要一)

This is just an example of the concept (although it works). Not intended for immediate reuse. Written quickly with lots of shortcuts, not production code, plenty of opportunities for improvement and optimization, may have silly mistakes, could use TagBuilder etc. etc. Could easily be modified to reuse the Wrapper class for different... wrappings (there may even be a generic one already in ASP.NET MVC - haven't had a need for one).

public static class WrapHelper
{
    private class Wrapper : IDisposable
    {
        private bool disposed;
        private readonly TextWriter writer;

        public Wrapper(HtmlHelper html)
        {
            this.writer = html.ViewContext.Writer;
        }

        public void Dispose()
        {
            if (disposed) return;

            disposed = true;

            writer.WriteLine("  </div>");
            writer.WriteLine("</div>");
        }
    }

    public static IDisposable Wrap(this HtmlHelper html, string title)
    {
        TextWriter writer = html.ViewContext.Writer;

        writer.WriteLine("<div class=\"module\">");
        writer.WriteLine("  <h3>" + html.Encode(title) + "</h3>");
        writer.WriteLine("  <div>");

        return new Wrapper(html);
    }
}

用法:

@using (Html.Wrap("Title"))
{
    <p>My very own markup.</p>
}

这篇关于MVC 3剃须刀,具有自定义标记/条助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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