Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net MVC dynamic Html attributes

I have few elements on my view textboxes , dropdowns etc. All of them have some unique attributes created like that

<%: Html.DropDownListFor(model => model.MyModel.MyType, EnumHelper.GetSelectList< MyType >(),new { @class = "someclass", @someattrt = "someattrt"})%>

I would like to create a read only version of my page by setting another attribute disabled.

Does anybody know how can I do it using variable that can be set globally?

Something like:

If(pageReadOnly){
isReadOnlyAttr  = @disabled = "disabled";
}else 
{
isReadOnlyAttr   =”” 
} 

<%: Html.DropDownListFor(model => model.MyModel.MyType, EnumHelper.GetSelectList< MyType >(),new { @class = "someclass", @someattrt = "someattrt",isReadOnlyAttr})%>

I don’t want to use JavaScript to do that

like image 471
Bart Avatar asked Jan 27 '11 11:01

Bart


1 Answers

I have done something similar to what you are after I think - basically I have a couple of different users of the system and one set have read-only privileges on the website. In order to do this I have a variable on each view model:

public bool Readonly { get; set; }

which is set in my model/business logic layer depending on their role privileges.

I then created an extension to the DropDownListFor Html Helper that accepts a boolean value indicating whether the drop-down list should be read only:

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;

public static class DropDownListForHelper
{
    public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> dropdownItems, bool disabled)
    {
        object htmlAttributes = null;

        if(disabled)
        {
            htmlAttributes = new {@disabled = "true"};
        }

        return htmlHelper.DropDownListFor<TModel, TProperty>(expression, dropdownItems, htmlAttributes);
    }
}

Note that you can create other instances that take more parameters also.

Than in my view I simply imported the namespace for my html helper extension and then passed in the view model variable readonly to the DropDownListFor Html helper:

<%@ Import Namespace="MvcApplication1.Helpers.HtmlHelpers" %>

<%= Html.DropDownListFor(model => model.MyDropDown, Model.MyDropDownSelectList, Model.Readonly)%>

I did the same for TextBoxFor, TextAreaFor and CheckBoxFor and they all seem to work well. Hope this helps.

like image 136
JayneT Avatar answered Sep 19 '22 21:09

JayneT