我需要能够从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扩展方法,但我不确定解析属性的最佳方法。
答案 0 :(得分:-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结果等内容产生影响。