我需要能够解析来自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扩展方法来实现这一点,但我不确定解析属性的最佳方式。
发布于 2012-07-14 09:06:54
要实现您想要的功能,一个想法是使用全局操作过滤器。这将获取操作的结果,并允许您在将它们发送回浏览器之前对其进行修改。我使用此技术将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结果等内容。
https://stackoverflow.com/questions/11478035
复制相似问题