Add RadioButtonList and Cascading DropDownList in ASP.Net MVC

Last Reply 9 days ago By dharmendr

Posted 12 days ago

Sir,

I have created a registration form using MVC 5 in Visual Studio 2017 Community Edition.

I didn't used Entity Framework. The registration page I have created is displaying Textboxes for all fields. 

I want to add RadiobuttonList for Gender with "Male" & "Female" option and also cascading dropdowns for State & District.

How should I achieve this? below is my code

Create.vbhtml

@ModelType amarnathShrineapp.Register
@Code
    ViewData("Title") = "Create"
End Code 

@Using (Html.BeginForm()) 
    @Html.AntiForgeryToken()    
    @<div class="form-horizontal">
        <h4>Registration For Yatra Parchi</h4>
        <hr />
        @Html.ValidationSummary(True, "", New With { .class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(Function(model) model.yatri_name, htmlAttributes:= New With { .class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(Function(model) model.yatri_name, New With { .htmlAttributes = New With { .class = "form-control" } })
                @Html.ValidationMessageFor(Function(model) model.yatri_name, "", New With { .class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(Function(model) model.yatri_state, htmlAttributes:=New With {.class = "control-label col-md-2"})
            <div class="col-md-10">
                @Html.EditorFor(Function(model) model.yatri_state, New With {.htmlAttributes = New With {.class = "form-control"}})
                @Html.ValidationMessageFor(Function(model) model.yatri_state, "", New With {.class = "text-danger"})
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(Function(model) model.yatri_district, htmlAttributes:= New With { .class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(Function(model) model.yatri_district, New With { .htmlAttributes = New With { .class = "form-control" } })
                @Html.ValidationMessageFor(Function(model) model.yatri_district, "", New With { .class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
End Using
<div>
    @Html.ActionLink("Back to List", "Index")
</div>

 

Register.vb 

Imports System.ComponentModel

Public Class Register
    Public Property yatri_userid As String

    <DisplayName("Full Name")>
    Public Property yatri_name As String

    <DisplayName("State")>
    Public Property yatri_state As String

    <DisplayName("District")>
    Public Property yatri_district As String

    <DisplayName("Date of Birth")>
    Public Property yatri_dob As Date

    <DisplayName("Gender")>
    Public Property yatri_gender As String

    <DisplayName("Next Kin Full Name")>
    Public Property yatri_nextkinname As String

    <DisplayName("Relation with Kin")>
    Public Property yatri_kinrelation As String

    <DisplayName("Mobile")>
    Public Property yatri_mobile As String

    <DisplayName("Medical Certificate Issue Authority")>
    Public Property med_issu_authority As String

    <DisplayName("Medical Certificate Issue State")>
    Public Property med_issu_state As String

    <DisplayName("Medical Certificate Issue District")>
    Public Property med_issu_district As String

End Class

RegisterController.vb 

Imports System.Web.Mvc
Imports System.Data.SqlClient

Namespace Controllers
    Public Class RegisterController
        Inherits Controller

        ' GET: Register
        <HttpGet()>
        Function Index() As ActionResult
            Return View()
        End Function

        ' GET: Register/Create
        <HttpGet()>
        Function Create() As ActionResult
            Return View(New Register)
        End Function

        ' POST: Register/Create
        <HttpPost()>
        Function Create(ByVal registerModel As Register) As ActionResult
            'Try
            ' TODO: Add insert logic here
            
            Return RedirectToAction("Create")

        End Function
    End Class
End Namespace

 

Posted 9 days ago

Hi Sumeet,

Using the below article i have created the example.

Cascading (Dependent) Country State City DropDownLists using jQuery AJAX in ASP.Net MVC

Check this example. Now please take its reference and correct your code.

Namespaces

C#

using System.Configuration;
using System.Data.SqlClient;

VB.Net

Imports System.Configuration
Imports System.Data.SqlClient

Model

C#

using System.ComponentModel;
using System.Web.Mvc;

public class Register
{
    public Register()
    {
        this.States = new List<SelectListItem>();
        this.Cities = new List<SelectListItem>();
    }
    public List<SelectListItem> States { get; set; }
    public List<SelectListItem> Cities { get; set; }

    [DisplayName("Full Name")]
    public string Name { get; set; }
    [DisplayName("State")]
    public string State { get; set; }
    [DisplayName("City")]
    public string City { get; set; }
    [DisplayName("Gender")]
    public string Gender { get; set; }
    [DisplayName("Mobile")]
    public Int64 Mobile { get; set; }
}

VB.Net

Imports System.ComponentModel
Imports System.Web.Mvc

Public Class Register
    Public Sub New()
        Me.States = New List(Of SelectListItem)()
        Me.Cities = New List(Of SelectListItem)()
    End Sub

    Public Property States As List(Of SelectListItem)
    Public Property Cities As List(Of SelectListItem)
    <DisplayName("Full Name")>
    Public Property Name As String
    <DisplayName("State")>
    Public Property State As String
    <DisplayName("City")>
    Public Property City As String
    <DisplayName("Gender")>
    Public Property Gender As String
    <DisplayName("Mobile")>
    Public Property Mobile As Int64
End Class

Controller

C#

public class HomeController : Controller
{
    // GET: /Home/
    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public ActionResult Create()
    {
        Register model = new Register();
        model.States = PopulateDropDown("SELECT StateId, StateName FROM States", "StateName", "StateId");
        return View(model);
    }

    [HttpPost]
    public JsonResult AjaxMethod(string type, int? value)
    {
        type = "State";
        value = 1;
        Register model = new Register();
        switch (type)
        {
            case "State":
                model.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = " + value, "CityName", "CityId");
                break;
        }
        return Json(model);
    }

    [HttpPost]
    public ActionResult Create(Register registerModel)
    {
        // Do your Task.   
        return RedirectToAction("Create");
    }

    private static List<SelectListItem> PopulateDropDown(string query, string textColumn, string valueColumn)
    {
        List<SelectListItem> items = new List<SelectListItem>();
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(query))
            {
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        items.Add(new SelectListItem
                        {
                            Text = sdr[textColumn].ToString(),
                            Value = sdr[valueColumn].ToString()
                        });
                    }
                }
                con.Close();
            }
        }

        return items;
    }
}

VB.Net

Public Class HomeController
    Inherits Controller

    Public Function Index() As ActionResult
        Return View()
    End Function

    <HttpGet>
    Public Function Create() As ActionResult
        Dim model As Register = New Register()
        model.States = PopulateDropDown("SELECT StateId, StateName FROM States", "StateName", "StateId")
        Return View(model)
    End Function

    <HttpPost>
    Public Function AjaxMethod(ByVal type As String, ByVal value As Integer?) As JsonResult
        Dim model As Register = New Register()
        Select Case type
            Case "State"
                model.Cities = PopulateDropDown("SELECT CityId, CityName FROM Cities WHERE StateId = " & value, "CityName", "CityId")
        End Select

        Return Json(model)
    End Function

    <HttpPost>
    Public Function Create(ByVal registerModel As Register) As ActionResult
        Return RedirectToAction("Create")
    End Function

    Private Shared Function PopulateDropDown(ByVal query As String, ByVal textColumn As String, ByVal valueColumn As String) As List(Of SelectListItem)
        Dim items As List(Of SelectListItem) = New List(Of SelectListItem)()
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using con As SqlConnection = New SqlConnection(constr)
            Using cmd As SqlCommand = New SqlCommand(query)
                cmd.Connection = con
                con.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        items.Add(New SelectListItem With {
                            .Text = sdr(textColumn).ToString(),
                            .Value = sdr(valueColumn).ToString()
                        })
                    End While
                End Using
                con.Close()
            End Using
        End Using

        Return items
    End Function
End Class

View

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Create</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <script type="text/javascript">
        $(function () {
            $("select").each(function () {
                if ($(this).find("option").length <= 1) {
                    $(this).attr("disabled", "disabled");
                }
            });

            $("#State").change(function () {
                var value = 0;
                if ($(this).val() != "") {
                    value = $(this).val();
                }
                var id = $(this).attr("id");
                $.ajax({
                    type: "POST",
                    url: "/Home/AjaxMethod",
                    data: '{type: "' + id + '", value: ' + value + '}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        var dropDownId;
                        var list;
                        switch (id) {
                            case "State":
                                dropDownId = "#City";
                                list = response.Cities;
                                DisableDropDown("#City");
                                PopulateDropDown("#City", list);
                                break;
                        }

                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });

        function DisableDropDown(dropDownId) {
            $(dropDownId).attr("disabled", "disabled");
            $(dropDownId).empty().append('<option selected="selected" value="0">Please select</option>');
        }

        function PopulateDropDown(dropDownId, list) {
            if (list != null && list.length > 0) {
                $(dropDownId).removeAttr("disabled");
                $.each(list, function () {
                    $(dropDownId).append($("<option></option>").val(this['Value']).html(this['Text']));
                });
            }
        }
    </script>
</head>
<body>
    <div>
        <%using (Html.BeginForm("Create", "Home", FormMethod.Post))
          { %>
        <div class="form-horizontal">
            <h4>
                Registration For Yatra Parchi</h4>
            <hr />
            <div class="form-group">
                <div class="col-md-2">
                    <%:Html.LabelFor(model => model.Name)%>
                </div>
                <div class="col-md-10">
                    <%:Html.EditorFor(model => model.Name)%>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-2">
                    <%:Html.LabelFor(model => model.Gender)%>
                </div>
                <div class="col-md-10">
                    Male
                    <%:Html.RadioButtonFor(model=>model.Gender,"Male") %>
                    Female
                    <%:Html.RadioButtonFor(model=>model.Gender,"Female") %>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-2">
                    <%:Html.LabelFor(model => model.State)%>
                </div>
                <div class="col-md-10">
                    <%:Html.DropDownListFor(model => model.State, Model.States, "Please select")%>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-2">
                    <%:Html.LabelFor(model => model.City)%>
                </div>
                <div class="col-md-10">
                    <%:Html.DropDownListFor(model => model.City, Model.Cities, "Please select")%>
                </div>
            </div>
            <div class="form-group">
                <div class="col-md-2">
                    <%:Html.LabelFor(model => model.Mobile)%>
                </div>
                <div class="col-md-10">
                    <%:Html.EditorFor(model => model.Mobile)%>
                </div>
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
        <%} %>
    </div>
</body>
</html>

Screenshot

The Form

On Submit