加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

Asp.Net MVC自定义控件 – 容器

发布时间:2020-12-16 09:58:03 所属栏目:asp.Net 来源:网络整理
导读:有没有办法在Asp.Net MVC中帮助包装其他类似的html: div class="lightGreyBar_left" div class="lightGreyBar_right" !--Content-- h3 Profiles/h3 div class="divOption" %= Html.ActionLinkWithImage("Create new","add.png",Keys.Actions.CreateProfile,
有没有办法在Asp.Net MVC中帮助包装其他类似的html:

<div class="lightGreyBar_left">
    <div class="lightGreyBar_right">

        <!--Content-->
        <h3>
            Profiles</h3>
        <div class="divOption">
            <%= Html.ActionLinkWithImage("Create new","add.png",Keys.Actions.CreateProfile,"add")%>
        </div>
        <!--Content-->

    </div>
</div>

因此,帮助器将呈现包含作为参数传递给辅助方法的div和内容.

解决方法

看一下表单助手方法.它们提供如下语法:

<% using (Html.BeginForm()) { %>
    <p>Form contents go here.</p>
<% } %>

实现这种HTML帮助程序的模式比通常的“只返回HTML字符串”类型帮助程序稍微复杂一些.基本上,您的辅助方法将在调用时对Response.Write开始标记进行处理,并返回一些实现IDisposable的自定义对象.当处理返回值时,它应该响应.写入结束标记.

这是一个工作示例:

public static MyContainer WrapThis(this HtmlHelper html)
{
    html.ViewContext.HttpContext.Response.Write("<div><div>");
    return new MyContainer(html.ViewContext.HttpContext.Response);
}

public class MyContainer : IDisposable
{
    readonly HttpResponseBase _httpResponse;
    bool _disposed;

    public MyContainer(HttpResponseBase httpResponse)
    {
        _httpResponse = httpResponse;
    }

    public void Dispose()
    {
        if (!_disposed)
        {
            _disposed = true;
            _httpResponse.Write("</div></div>");
        }

        GC.SuppressFinalize(this);
    }
}

这将允许您将视图重写为:

<% using (Html.WrapThis()) { %>
    <h3>Profiles</h3>
    <div class="divOption">
        <%= Html.ActionLinkWithImage("Create new","add")%>
    </div>
<% } %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读