0

我需要能够解析 MvcHtmlString 中的属性(HtmlHelper 扩展的结果),以便我可以更新和添加它们。

例如,以这个 HTML 元素为例:

<input type="text" id="Name" name="Name" 
 data-val-required="First name is required.|Please provide a first name.">

我需要从中获取值data-val-required,将其拆分为两个属性,第二个值进入一个新属性:

<input type="text" id="Name" name="Name" 
 data-val-required="First name is required."
 data-val-required-summary="Please provide a first name.">

我正在尝试使用 HtmlHelper 扩展方法来执行此操作,但我不确定解析属性的最佳方法。

4

1 回答 1

-1

完成您想要的一个想法是使用全局操作过滤器。这将获取操作的结果,并允许您在将它们发送回浏览器之前对其进行修改。我使用这种技术将 CSS 类添加到页面的 body 标记中,但我相信它也适用于您的应用程序。

这是我使用的代码(归结为基础):

public class GlobalCssClassFilter : ActionFilterAttribute {
    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        //build the data you need for the filter here and put it into the filterContext
        //ex: filterContext.HttpContext.Items.Add("key", "value");

        //activate the filter, passing the HtppContext we will need in the filter.
        filterContext.HttpContext.Response.Filter = new GlobalCssStream(filterContext.HttpContext);
    }
}

public class GlobalCssStream : MemoryStream {
    //to store the context for retrieving the area, controller, and action
    private readonly HttpContextBase _context;

    //to store the response for the Write override
    private readonly Stream _response;

    public GlobalCssStream(HttpContextBase context) {
        _context = context;
        _response = context.Response.Filter;
    }

    public override void Write(byte[] buffer, int offset, int count) {
        //get the text of the page being output
        var html = Encoding.UTF8.GetString(buffer);

        //get the data from the context
        //ex var area = _context.Items["key"] == null ? "" : _context.Items["key"].ToString();

        //find your tags and add the new ones here
        //modify the 'html' variable to accomplish this

        //put the modified page back to the response.
        buffer = Encoding.UTF8.GetBytes(html);
        _response.Write(buffer, offset, buffer.Length);
    }
}

需要注意的一件事是,我相信 HTML 被缓冲到 8K 块中,因此如果您的页面超过该大小,您可能必须确定如何处理它。对于我的应用程序,我不必处理这个问题。

此外,由于所有内容都是通过此过滤器发送的,因此您需要确保所做的更改不会影响 JSON 结果等内容。

于 2012-07-14T01:06:53.587 回答