0
votes

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);
}
1
How to make disable or readonly id FlagAccessEdit =false? - Natarajan Veerasekaran
If this comment is part of the question you should edit it into the question and not as a comment. - Ravid Goldenberg
The answer by Ashish Shukla shows one solution, but what would be the point. There is no such thing as a readonly checkbox, and disabling it would mean you always post back false even if the checkbox is initially displayed as checked (true) which would no doubt screw up your app. If you want to do this, generate a hidden input for the value a some text (say "Yes" or "No") - user3559349

1 Answers

1
votes

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)