MVC 3的HtmlHelper扩展方法来回绕内容 [英] MVC 3 htmlhelper extension method to wrap around content
问题描述
我搜查,但对于MVC 3的HtmlHelper创建一个包装方法找不到任何快速解决方案。我正在寻找的是这样的:
I searched but could not find any quick solutions for an MVC 3 htmlhelper to create a wrapper method. What I'm looking for is something like:
@html.createLink("caption", "url")
{
<html> content in tags </html>
}
结果应该有
<a href="url" title="Caption">
<html> content in tags </html>
</a>
任何帮助。
推荐答案
,这是与BeginForm做的方法是,返回类型 MvcForm
impliments IDisposable的
这样一个使用
语句中使用时,的的Dispose
方法 MvcForm
写出结束&LT; /表格方式&gt;
标签
The way that this is done with BeginForm is that the return type MvcForm
impliments IDisposable
so that when used within a using
statement, the Dispose
method of MvcForm
writes out the closing </form>
tag.
您可以写,做同样的事情的扩展方法。
You can write an extension method that does exactly the same thing.
这里有一个我刚写证明。
Here's one I just wrote to demonstrate.
首先,扩展方法:
public static class ExtensionTest
{
public static MvcAnchor BeginLink(this HtmlHelper htmlHelper)
{
var tagBuilder = new TagBuilder("a");
htmlHelper.ViewContext.Writer
.Write(tagBuilder.ToString(
TagRenderMode.StartTag));
return new MvcAnchor(htmlHelper.ViewContext);
}
}
和这里是我们的新类型,MvcAnchor:
And here's our new type, MvcAnchor:
public class MvcAnchor : IDisposable
{
private readonly TextWriter _writer;
public MvcAnchor(ViewContext viewContext)
{
_writer = viewContext.Writer;
}
public void Dispose()
{
this._writer.Write("</a>");
}
}
在你的意见,你现在可以做的:
In your views you can now do:
@{
using (Html.BeginLink())
{
@Html.Raw("Hello World")
}
}
这产生的结果:
<a>Hello World</a>
拓展这种略带处理您的具体要求:
Expanding this slightly to deal with your exact requirement:
public static MvcAnchor BeginLink(this HtmlHelper htmlHelper,
string href,
string title)
{
var tagBuilder = new TagBuilder("a");
tagBuilder.Attributes.Add("href",href);
tagBuilder.Attributes.Add("title", title);
htmlHelper.ViewContext.Writer.Write(tagBuilder
.ToString(TagRenderMode.StartTag));
return new MvcAnchor(htmlHelper.ViewContext);
}
和我们的观点:
@{
using (Html.BeginLink("http://stackoverflow.com", "The Worlds Best Q&A site"))
{
@Html.Raw("StackOverflow - Because we really do care")
}
}
这将产生的结果:
which yields the result:
<a href="http://stackoverflow.com" title="The Worlds Best Q&A site">
StackOverflow - Because we really do care</a>
这篇关于MVC 3的HtmlHelper扩展方法来回绕内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!