自定义HTML助手:用&QUOT创建帮手;使用"声明支持 [英] Custom html helpers: Create helper with "using" statement support
本文介绍了自定义HTML助手:用&QUOT创建帮手;使用"声明支持的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在写我的第一个asp.net的MVC应用程序,我有一个关于自定义HTML佣工问题:
I'm writing my first asp.net mvc application and I have a question about custom Html helpers:
有关制作一个表格,你可以使用:
For making a form, you can use:
<% using (Html.BeginForm()) {%>
*stuff here*
<% } %>
我希望做一个自定义的HTML帮助类似的东西。 换句话说,我想改变:
I would like to do something similar with a custom HTML helper. In other words, I want to change:
Html.BeginTr();
Html.Td(day.Description);
Html.EndTr();
到
using Html.BeginTr(){
Html.Td(day.Description);
}
这可能吗?
推荐答案
下面是在C#中一个可能的重用实现:
Here is a possible reusable implementation in c# :
class DisposableHelper : IDisposable
{
private Action end;
// When the object is created, write "begin" function
public DisposableHelper(Action begin, Action end)
{
this.end = end;
begin();
}
// When the object is disposed (end of using block), write "end" function
public void Dispose()
{
end();
}
}
public static class DisposableExtensions
{
public static IDisposable DisposableTr(this HtmlHelper htmlHelper)
{
return new DisposableHelper(
() => htmlHelper.BeginTr(),
() => htmlHelper.EndTr()
);
}
}
在这种情况下, BeginTr
和 EndTr
直接写入响应流。如果您使用返回一个字符串的扩展方法,你会用得它们输出:
In this case, BeginTr
and EndTr
directly write in the response stream. If you use extension methods that return a string, you'll have to output them using :
htmlHelper.ViewContext.HttpContext.Response.Write(s)
这篇关于自定义HTML助手:用&QUOT创建帮手;使用&QUOT;声明支持的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文