How to set disabled in MVC htmlAttribute

后端 未结 8 2389
刺人心
刺人心 2020-12-30 02:06

When using an HTML Helper, what is the best method to set an attribute based on a condition. For example

<%if (Page.User.IsInRole(\"administrator\")) {%&g         


        
8条回答
  •  抹茶落季
    2020-12-30 02:36

    Using @SLaks suggestion to use an Extension method, and using Jeremiah Clark's example Extension method I've written an extension method so I can now do

    Html.TextBoxFor(m => m.FirstName,new{class='contactDetails', ...},Page.User.IsInRole("administrator"));
    

    Not Sure if there's a better method though

    public static class InputExtensions
    {
    
        public static IDictionary TurnObjectIntoDictionary(object data)
        {
            var attr = BindingFlags.Public | BindingFlags.Instance;
            var dict = new Dictionary();
            if (data == null)
                return dict;
            foreach (var property in data.GetType().GetProperties(attr))
            {
                if (property.CanRead)
                {
                    dict.Add(property.Name, property.GetValue(data, null));
                }
            }
            return dict;
    
        }
    
        public static MvcHtmlString TextBoxFor(this HtmlHelper htmlHelper, Expression> expression, object htmlAttributes, bool disabled)
        {
            IDictionary values =  TurnObjectIntoDictionary(htmlAttributes);
    
            if (disabled)
                values.Add("disabled","true");
    
    
            return htmlHelper.TextBoxFor(expression, values);
        }
    
        public static MvcHtmlString TextAreaFor(this HtmlHelper htmlHelper, Expression> expression, object htmlAttributes, bool disabled)
        {
            IDictionary values = TurnObjectIntoDictionary(htmlAttributes);
    
            if (disabled)
                values.Add("disabled", "true");
    
    
            return htmlHelper.TextAreaFor(expression, values);
        }
    
        public static MvcHtmlString CheckBoxFor(this HtmlHelper htmlHelper, Expression> expression, object htmlAttributes, bool disabled)
        {
            IDictionary values = TurnObjectIntoDictionary(htmlAttributes);
    
            if (disabled)
                values.Add("disabled", "true");
    
    
            return htmlHelper.CheckBoxFor(expression, values);
        }
    }
    

提交回复
热议问题