Share via


How to disable @Html.TextBox based on a condition ?

Question

Wednesday, April 4, 2018 9:43 PM

on my RazorView I have

@Html.TextBox("HistoryStartDate", DateTime.Today.AddDays(-90).Date.ToString("MM/dd/yyyy"), new { @class = "input-small date-input datepicker", maxlength = 10 ,disabled=false })

I have  Boolean variable defined in my Model

bool IsCustomer=false;

How to disable or enable the above textbox based on the IsCustomer flag ?

All replies (2)

Thursday, April 5, 2018 8:37 AM âś…Answered

Hi AspDevelopLife ,

You could also try to use below helper function :

@Html.TextBox("HistoryStartDate", DateTime.Today.AddDays(-90).Date.ToString("MM/dd/yyyy"), @getHtmlAttributes(Model.IsCustomer))


@functions {
    object getHtmlAttributes(bool IsCustomer)
    {
        if (!IsCustomer)
        {
            return new { @class = "input-small date-input datepicker", maxlength = 10, disabled = "disabled" };
        }
        return new { @class = "input-small date-input datepicker", maxlength = 10 };
    }
}

Best Regards,

Angie


Wednesday, April 4, 2018 10:50 PM

Of course, you can use an If statement and look at the Boolean value of the model property of the model passed into the view.

if (!Model.IsCustomer

{

    //do something

}

The do something would be to use JQuery and find the control by classname and change the disable attribute.

https://api.jquery.com/class-selector/

http://www.jquerybyexample.net/2012/07/how-to-disable-enable-element-with-jquery.html

The do something would also be to call a JavaScript function to execute the JQuery.

So you would have to get JavaScript and JQuery implemented in the view. It's something you can do, as an example.