【问题标题】:Creating Some thing @using (Html.BeginForm()) Helpers创建一些东西 @using (Html.BeginForm()) Helpers
【发布时间】:2011-09-24 15:17:11
【问题描述】:

在 Asp.net MVC3 中,当您编写以下代码时,它会自行生成包装 html

 @using (Html.BeginForm()) {
                @Html.ValidationMessageFor(model => model.Text)
}

它生成以下格式的代码,

<form method="post" action="/Feeds">
   <!-- Fields Here -->
</form>

我在@using (Html.BeginForm()) 中的问题自动在开头和结尾添加&lt;form&gt; 标签,我怎样才能创建类似我自己的东西。

我正在寻找类似下面的东西

@using (Html.BeginMYCUSTOMDIV())
  {
        I am text inside div
  }

预期生成的输出

<div class="customDivClass">
I am text inside div
</div>

【问题讨论】:

标签: asp.net-mvc asp.net-mvc-3


【解决方案1】:

类似的东西:

public class MyDiv : IDisposable
{
    private readonly TextWriter _writer;
    public MyDiv(TextWriter writer)
    {
        _writer = writer;
    }

    public void Dispose()
    {
        _writer.WriteLine("</div>");
    }
}

public static class MyExtensions
{
    public static MyDiv BeginMYCUSTOMDIV(this HtmlHelper htmlHelper)
    {
        var div = new TagBuilder("div");
        div.AddCssClass("customDivClass");
        htmlHelper.ViewContext.Writer.WriteLine(div.ToString(TagRenderMode.StartTag));
        return new MyDiv(htmlHelper.ViewContext.Writer);
    }
}

在视图中:

@using (Html.BeginMYCUSTOMDIV())
{
    <span>Hello</span>
}

生成:

<div class="customDivClass">
    <span>Hello</span>
</div>

【讨论】:

  • CS1061: 'System.Web.Mvc.HtmlHelper&lt;dynamic&gt;' does not contain a definition for 'BeginMYCUSTOMDIV' and no extension method 'BeginMYCUSTOMDIV' accepting a first argument of type 'System.Web.Mvc.HtmlHelper&lt;dynamic&gt;' could be found (are you missing a using directive or an assembly reference?) 收到此错误
  • @Rusi Nova,您是否将包含 MyExtensions 静态类的命名空间纳入您的视图范围?喜欢 Razor 页面顶部的 @using Foo.Bar?或者喜欢将此命名空间添加到~/Views/web.config&lt;namespaces&gt; 部分?这是扩展方法的工作方式。 ASP.NET MVC 中的 Html 助手只不过是扩展方法。因此,必须将它们纳入范围供您使用。
  • 哦,谢谢!明白了你的意思,现在它运行良好。我打算将MyExtensions 类转移到System.Web.Mvc.Html 命名空间内,这是个好主意吗??
  • @Rusi Nova,是的,为什么不呢。这样它将可以自动访问,因为 System.Web.Mvc.Html 命名空间在范围内。你还有什么想问的吗?
  • thanx, "That way it will be accessible automatically": 这就是我决定这样做的原因。
【解决方案2】:

如果我没记错的话,Html.BeginForm() 返回一个 IDisposable 对象。在using块中使用时,会调用对象的Dispose方法,该方法负责将结束标记写入输出。

how does using HtmlHelper.BeginForm() work?

Html.BeginForm() type of extension

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多