在 Asp.net MVC3中,当您编写下面的代码时,它会自动生成包装html @using (Html.BeginForm()) { @Html.ValidationMessageFor(model = model.Text)} 它生成以下格式的代码, form method="post" action="/Feeds" !-- Fields Here -
@using (Html.BeginForm()) { @Html.ValidationMessageFor(model => model.Text) }
它生成以下格式的代码,
<form method="post" action="/Feeds"> <!-- Fields Here --> </form>
我在@using(Html.BeginForm())中的问题会自动添加< form>标签在开头和结尾,我怎样才能创建类似我自己的东西.
我正在寻找下面的东西
@using (Html.BeginMYCUSTOMDIV()) { I am text inside div }
预期的生成输出
<div class="customDivClass"> I am text inside div </div>一些事情:
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>