Set disable attribute based on a condition for Html.TextBoxFor

As a web developer, you may often encounter scenarios where you need to conditionally enable or disable certain form fields based on user interactions or specific conditions. One common requirement is to dynamically set the disabled attribute for an Html.TextBoxFor control in an ASP.NET MVC application. In this blog post, we will explore how to achieve this functionality using C# code snippets and demonstrate a practical example.

Step 1: Create a Model

First, let's create a simple model class to represent the data we want to capture in our form. Open the Models folder and add a new class file called Person.cs. Replace the contents of the file with the following code:

using System.ComponentModel.DataAnnotations;

namespace YourProject.Models
{
    public class Person
    {
        [Required]
        public string Name { get; set; }

        public bool IsDisabled { get; set; }
    }
}

Step 2: Create a Controller

Next, we need to create a controller that will handle the rendering of the view and the logic for enabling or disabling the textbox based on the IsDisabled property value. In the Controllers folder, add a new controller called HomeController.cs with the following code:

using System.Web.Mvc;
using YourProject.Models;

namespace YourProject.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var person = new Person
            {
                IsDisabled = true // Set this based on your condition
            };

            return View(person);
        }
    }
}

Step 3: Create a View

Now, let's create a view to display the form and the Html.TextBoxFor control with the dynamically set disabled attribute. In the Views folder, create a new folder called Home and add a new view file called Index.cshtml inside it. Replace the contents of the file with the following code:

@model YourProject.Models.Person

@{
    ViewBag.Title = "Home Page";
}

<h2>Form</h2>

@using (Html.BeginForm())
{
    <div class="form-group">
        @Html.LabelFor(model => model.Name)
        @Html.TextBoxFor(model => model.Name, new { @disabled = Model.IsDisabled })
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    <button type="submit" class="btn btn-primary">Submit</button>
}

In this blog post, we learned how to dynamically set the disabled attribute for an Html.TextBoxFor control in an ASP.NET MVC application. By utilizing the @disabled attribute with a value from the model, we can conditionally enable or disable the textbox based on specific conditions.

 
Best quality Asp .Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
8 + 5 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice