0

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

例如,借此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扩展方法来做到这一点,但我不确定解析属性的最佳方式。

+2

哇,让我们从头开始,因为这种气味/臭味/发出窒息的odeur。你究竟想达到什么目的?请不要回答:'从MvcHtmlString解析属性。我期待着一个关于你最初目标的答案。因为'从MvcHtmlString'解析属性可能是达到最初目标的一种方法。可能还有其他方法。更好的方法。但是如果不知道最初的目标,很难为您提供更好的方法。 – 2012-07-13 20:46:07

+1

那么,就这个问题而言,我真的只是对如何解析由其他帮助者生成的属性感兴趣。 :)但是我会幽默地说,我们的用户体验团队需要为我们的用户提供单独的验证信息 - 字段级和总结级。使用内置验证,ModelStateDictionary仅支持一条消息。因此,如果不完全重写内置验证,这是我可以提出的最佳方法。如果您有任何想法,请告诉我们,我们可以脱机讨论(以免劫持此主题)。 – 2012-07-13 20:49:31

+0

而且,为了记录,我同意:它确实有异味。厉害。 – 2012-07-13 20:50:34

回答

-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结果等内容。