How to set disabled in MVC htmlAttribute

后端 未结 8 2326
刺人心
刺人心 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<string, object> TurnObjectIntoDictionary(object data)
        {
            var attr = BindingFlags.Public | BindingFlags.Instance;
            var dict = new Dictionary<string, object>();
            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<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes, bool disabled)
        {
            IDictionary<string, object> values =  TurnObjectIntoDictionary(htmlAttributes);
    
            if (disabled)
                values.Add("disabled","true");
    
    
            return htmlHelper.TextBoxFor(expression, values);
        }
    
        public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes, bool disabled)
        {
            IDictionary<string, object> values = TurnObjectIntoDictionary(htmlAttributes);
    
            if (disabled)
                values.Add("disabled", "true");
    
    
            return htmlHelper.TextAreaFor(expression, values);
        }
    
        public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, object htmlAttributes, bool disabled)
        {
            IDictionary<string, object> values = TurnObjectIntoDictionary(htmlAttributes);
    
            if (disabled)
                values.Add("disabled", "true");
    
    
            return htmlHelper.CheckBoxFor(expression, values);
        }
    }
    
    0 讨论(0)
  • 2020-12-30 02:42

    It works for me as well...

    <%: Html.DropDownList("SportID", (SelectList)ViewData["SportsSelectList"], "-- Select --", new { @disabled = "disabled", @readonly = "readonly" })%>
    
    <%= Html.CheckBoxFor(model => model.IsActive, new { @disabled = "disabled", @readonly = "readonly" })%>
    
    0 讨论(0)
提交回复
热议问题