In this article I will explain with an example, how to enable or disable TextBox from Controller in ASP.Net MVC Razor.
A Boolean value will be stored in a ViewBag object inside the Controller’s Action method and the value of the ViewBag object will be used to enable or disable the TextBox in View.
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
 
Action method for handling POST operation
When the Form is submitted, the following Action method is called. The value of HasPassport CheckBox is received in the hasPassport parameter.
The received Boolean value is stored into a ViewBag object which will be later used in the View for enabling or disabling the TextBox.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Index(bool hasPassport)
    {
        ViewBag.HasPassport = hasPassport;
        return View();
    }
}
 
 
View
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
Inside the View, the following two HTML Helper functions are used:-
1. Html.CheckBox – Creating a CheckBox element.
2. Html.TextBox – Creating a TextBox element.
3. Html.Label – Displaying the Labels for the Input elements.
The CheckBox has been assigned a JavaScript OnClick event handler. When the CheckBox is clicked i.e. checked or unchecked, the Form will be submitted.
If the ViewBag.HasPassport variable has value True, then the TextBox is enabled else the TextBox is disabled by setting the disabled Attribute.
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        @Html.CheckBox("HasPassport", false, new { @onclick = "document.forms[0].submit();" })
        @Html.Label("Do you have Passport?", new { @for = "HasPassport" })
        <br/>
        @Html.Label("Passport Number: ")
 
        if(Convert.ToBoolean(ViewBag.HasPassport))
        {
            @Html.TextBox("txtPassportNumber")
        }
        else
        {
            @Html.TextBox("txtPassportNumber", "", new { @disabled = "disabled" })
        }
    }
</body>
</html>
 
 
Screenshot
Enable or Disable TextBox from Controller in ASP.Net MVC
 
 
Downloads