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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – 创建MVC3剃刀助手,如Helper.BeginForm()前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想创建一个帮助器,我可以在括号之间添加内容,就像Helper.BeginForm()一样。我不介意为我的帮手创建一个开始,结束,但是这样做很简单和容易。

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

就像是

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

参数“full”是该div的css id,“title”是该节的标题

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

提前感谢任何帮助。

解决方法

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

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

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

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

  1. public class MySection : IDisposable {
  2. protected HtmlHelper _helper;
  3.  
  4. public MySection(HtmlHelper helper,string className,string title) {
  5. _helper = helper;
  6. _helper.ViewContext.Writer.Write(
  7. "<div class=\"" + className + "\" title=\"" + title + "\">"
  8. );
  9. }
  10.  
  11. public void Dispose() {
  12. _helper.ViewContext.Writer.Write("</div>");
  13. }
  14. }

现在该类型可用,您可以扩展HtmlHelper。

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

猜你在找的asp.Net相关文章