How to add additional attribute for dynamic object?

How to make disable or readonly if FlagAccessEdit =false?

public static MvcHtmlString CCheckBox(this HtmlHelper htmlHelper, 
string name,object htmlAttributes, 
bool FlagAccessEdit = true, bool FlagAccessView = true)
{

            if (!FlagAccessView)
                return MvcHtmlString.Empty;
            else if (!FlagAccessEdit && FlagAccessView)
            {
                return htmlHelper.CheckBox(name, htmlAttributes);
            }
            else
                return htmlHelper.CheckBox(name, htmlAttributes);
}

Upvotes: 0

Views: 636

Answers (1)

Ashish Shukla
Ashish Shukla

Reputation: 1294

You need to get the existing htmlAttribute and add disabled or read-only based on your condition. Below is the correct code

Helper method

public static MvcHtmlString CCheckBox(this HtmlHelper htmlHelper,
        string name, object htmlAttributes,bool FlagAccessEdit = true, 
        bool FlagAccessView = true)
    {
        //get the htmlAttribute
        IDictionary<string, object> attributes = new RouteValueDictionary(htmlAttributes);

        if (!FlagAccessView)
            return MvcHtmlString.Empty;
        else if (!FlagAccessEdit && FlagAccessView)
        {
            //Add the disabled attribute
            attributes.Add("disabled", "disabled");
            return htmlHelper.CheckBox(name, attributes);
        }
        else
        {
            return htmlHelper.CheckBox(name, htmlAttributes);
        }

    }

Call the method like below

@Html.CCheckBox("chkCheckbox", new { id="chkDemo"},false,true)

Upvotes: 2

Related Questions