Dropdownlist with inline selectlist in MVC 5


In this post we will learn how to implement dropdownlist with inline selectlist in MVC 5.

lets start by creating action method in controller

Action Method
public ActionResult Index2(string gender)
{
    ViewBag.gender = gender;
    return View();
}

 

add a view for this action method and write the following code

View
@{
    ViewBag.Title = "Dropdownlist with inline selectlist || Chikkanti.wordpress.com";
}

<h2>Dropdownlist with inline selectlist</h2>

@using (Html.BeginForm())
{
    @Html.Label("Gender : ")
    @Html.DropDownList("gender", new SelectList(new List<SelectListItem>() {
    new SelectListItem(){Text="Male", Value="Male"},
    new SelectListItem(){Text="Female", Value="Female"}
    }, "Value", "Text", "..Select.."))
    <input type="submit" name="name" value="Submit" />
    if (!string.IsNullOrEmpty(ViewBag.gender))
    {
        string message = "Selected Gender : " + ViewBag.gender;
        @Html.Label(message)
    }
}

 

Now Rebuild the application and run

image

image

Advertisements

Cascading Dropdownlist with model binding in MVC 5


In this post we will learn how to Implement Cascading dropdownlist with model binding in MVC 5

Here I am going to implement Cascading dropdown with country, state and city example. To get Country, state and cities data I am writing three methods called GetCountries(), GetStates(int CountryId) and GetCities(int StateId)

Here GetCountries method is accepting no parameters and it will return Countries selectlist. GetStates is accepting a parameter countryId of type int and it will return States selectlist, GetCities is accepting a parameter StateId of type int and it will return Cities selectlist

Data source Methods
[NonAction]
private SelectList GetCountries()
{
return new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = true, Text = “–Select Country–“, Value = “0”},
new SelectListItem { Selected = false, Text = “India”, Value = “1”},
new SelectListItem {Selected = false, Text = “USA”, Value = “2”},
new SelectListItem{ Selected = false,Text = “UK”, Value = “3”},
}, “Value”, “Text”, “0”);
}
[NonAction]
private SelectList GetStates(int CountryId)
{
if (CountryId == 1)
{
return new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = true, Text = “–Select State–“, Value = “0”},
new SelectListItem { Selected = false, Text = “Andhrapradesh”, Value = “1”},
new SelectListItem {Selected = false, Text = “Tamilanadu”, Value = “2”},
new SelectListItem{ Selected = false,Text = “Karnataka”, Value = “3”},
}, “Value”, “Text”, “0”);
}
else if (CountryId == 2)
{
return new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = true, Text = “–Select State–“, Value = “0”},
new SelectListItem { Selected = false, Text = “California”, Value = “4”},
new SelectListItem {Selected = false, Text = “Virginia”, Value = “5”},
new SelectListItem{ Selected = false,Text = “Washington”, Value = “6”},
}, “Value”, “Text”, “0”);
}
else if (CountryId == 3)
{
return new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = true, Text = “–Select State–“, Value = “0”},
new SelectListItem { Selected = false, Text = “Cambridge”, Value = “7”},
new SelectListItem {Selected = false, Text = “Norwich”, Value = “8”},
new SelectListItem{ Selected = false,Text = “Wells”, Value = “9”},
}, “Value”, “Text”, “0”);
}
return null;
}
[NonAction]
private SelectList GetCities(int StateId)
{
if (StateId == 1)
{
return new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = true, Text = “–Select City–“, Value = “0”},
new SelectListItem { Selected = false, Text = “Ongole”, Value = “1”},
new SelectListItem {Selected = false, Text = “Guntur”, Value = “2”},
new SelectListItem{ Selected = false,Text = “Kadapa”, Value = “3”},
}, “Value”, “Text”, “0”);
}
else if (StateId == 2)
{
return new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = true, Text = “–Select City–“, Value = “0”},
new SelectListItem { Selected = false, Text = “TN-City1”, Value = “4”},
new SelectListItem {Selected = false, Text = “TN-City2”, Value = “5”},
new SelectListItem{ Selected = false,Text = “TN-City3”, Value = “6”},
}, “Value”, “Text”, “0”);
}
else if (StateId == 3)
{
return new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = true, Text = “–Select City–“, Value = “0”},
new SelectListItem { Selected = false, Text = “K-City1”, Value = “7”},
new SelectListItem {Selected = false, Text = “K-City2”, Value = “8”},
new SelectListItem{ Selected = false,Text = “K-City3”, Value = “9”},
}, “Value”, “Text”, “0”);
}
if (StateId == 4)
{
return new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = true, Text = “–Select City–“, Value = “0”},
new SelectListItem { Selected = false, Text = “C-City1”, Value = “10”},
new SelectListItem {Selected = false, Text = “C-City2”, Value = “11”},
new SelectListItem{ Selected = false,Text = “C-City3”, Value = “12”},
}, “Value”, “Text”, “0”);
}
else if (StateId == 5)
{
return new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = true, Text = “–Select City–“, Value = “0”},
new SelectListItem { Selected = false, Text = “V-City1”, Value = “13”},
new SelectListItem {Selected = false, Text = “V-City2”, Value = “14”},
new SelectListItem{ Selected = false,Text = “V-City3”, Value = “15”},
}, “Value”, “Text”, “0”);
}
else if (StateId == 6)
{
return new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = true, Text = “–Select City–“, Value = “0”},
new SelectListItem { Selected = false, Text = “WA-City1”, Value = “16”},
new SelectListItem {Selected = false, Text = “WA-City2”, Value = “17”},
new SelectListItem{ Selected = false,Text = “WA-City3”, Value = “18”},
}, “Value”, “Text”, “0”);
}
if (StateId == 7)
{
return new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = true, Text = “–Select City–“, Value = “0”},
new SelectListItem { Selected = false, Text = “CB-City1”, Value = “19”},
new SelectListItem {Selected = false, Text = “CB-City2”, Value = “20”},
new SelectListItem{ Selected = false,Text = “CB-City3”, Value = “21”},
}, “Value”, “Text”, “0”);
}
else if (StateId == 8)
{
return new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = true, Text = “–Select State–“, Value = “0”},
new SelectListItem { Selected = false, Text = “N-City1”, Value = “22”},
new SelectListItem {Selected = false, Text = “N-City2”, Value = “23”},
new SelectListItem{ Selected = false,Text = “N-City3”, Value = “24”},
}, “Value”, “Text”, “0”);
}
else if (StateId == 9)
{
return new SelectList(new List<SelectListItem>{
new SelectListItem { Selected = true, Text = “–Select State–“, Value = “0”},
new SelectListItem { Selected = false, Text = “W-City1”, Value = “25”},
new SelectListItem {Selected = false, Text = “W-City2”, Value = “26”},
new SelectListItem{ Selected = false,Text = “W-City3”, Value = “27”},
}, “Value”, “Text”, “0”);
}
return null;
}

After preparing data elements, let’s get into the implementation

first create model as follows

Address Model
public class Address
{
//Holds Selected Country Id
public int SelectedCountryId { get; set; }
//Holds Selected State Id
public int SelectedStateId { get; set; }
//Holds Selected City Id
public int SelectedCityId { get; set; }
//List of countries
public System.Web.Mvc.SelectList Countries { get; set; }
//List of States
public System.Web.Mvc.SelectList States { get; set; }
//List of Cities
public System.Web.Mvc.SelectList Cities { get; set; }

}

In this Model we have 3 list members and 3 primitive members

Now add 2 Action methods in the controller one is for GET call and another is for POST call

Controller
// GET: Index
public ActionResult Index()
{
Address model = new Address() {
Countries = this.GetCountries()
};
return View(model);
}
// POST: Index
[HttpPost]
public ActionResult Index(Address model)
{
model.States = null;
model.Cities = null;
if (model.Countries == null)
{
model.Countries = this.GetCountries();
}
if (model.SelectedCountryId > 0 && model.States == null)
{
model.States = this.GetStates(model.SelectedCountryId);
}
if (model.SelectedStateId > 0)
{
model.Cities = this.GetCities(model.SelectedStateId);
}
return View(model);
}

Now add a view for the action method and write the following code in it

View
@model WebApplication5.Models.Address
@{
ViewBag.Title = “Nested Dropdownlist with model binding || Chikkanti.wordpress.com”;
}

<h2>Nested Dropdownlist with model binding</h2>

@using (Html.BeginForm(null, null, FormMethod.Post, new { @Id = “formAddress” }))
{
if (Model.Countries != null)
{
@Html.Label(“County: “)
@Html.DropDownListFor(m => m.SelectedCountryId, Model.Countries, new { onchange = “Submitform()” })<br />
}
if (Model.States != null)
{
@Html.Label(“State: “)
@Html.DropDownListFor(m => m.SelectedStateId, Model.States, new { onchange = “Submitform()” })<br />
}
if (Model.Cities != null)
{
@Html.Label(“City: “)
@Html.DropDownListFor(m => m.SelectedCityId, Model.Cities)
}<br />
<input type=”submit” name=”name” value=”Submit” /><br />
if (Model.SelectedCountryId > 0 && Model.Countries != null)
{
@Html.Label(“Selected Country : “)
@Html.Label(Model.Countries.Where(c => c.Value == Model.SelectedCountryId.ToString()).Select(c => c.Text).FirstOrDefault())
<br />
}
if (Model.SelectedStateId > 0 && Model.States != null)
{
@Html.Label(“Selected State : “)
@Html.Label(Model.States.Where(c => c.Value == Model.SelectedStateId.ToString()).Select(c => c.Text).FirstOrDefault())
<br />
}
if (Model.SelectedCityId > 0 && Model.Cities != null)
{
@Html.Label(“Selected City : “)
@Html.Label(Model.Cities.Where(c => c.Value == Model.SelectedCityId.ToString()).Select(c => c.Text).FirstOrDefault())
<br />
}
}

<script>
function Submitform() {
var form = document.getElementById(“formAddress”);
form.submit();
}
</script>

In the view we are using onchange event for dropdownlist to submit the form and gets the states and cities list on demand.

Onchange is a javascript event, trigger on chage of selected value of a dropdownlist and inside this event we are submitting the form using javascript.

Now Rebuild the application and run.

image

image

image

image

How to validate Dropdownlist in MVC 5 using model


In this post we will learn how to validate Dropdownlist using Model in MVC 5

First create model as follows

Model:

Model
    public class CountryModel
    {
        [Required(ErrorMessage="Country Required.")]
        public int SelectedCountryId { get; set; }
        public System.Web.Mvc.SelectList Countries { get; set; }
    }

 

In the model we have added the following line

[Required(ErrorMessage="Country Required.")]

Required is a attribute applied on SelectedCountryId.

this Required attribute is available in the namespace

using System.ComponentModel.DataAnnotations;

Required attribute force the user to send SelectedCountryId to the server, otherwise it will display the error message mentioned in the model as follows

(ErrorMessage="Country Required.")

Now write the action method in controller as follows

Action Method
        public ActionResult Index(CountryModel model)
        {
            if (model.Countries == null)
            {
                model.Countries = new SelectList(new List<SelectListItem>()
                {
                    new SelectListItem() { Text= "India", Value = "1" },
                    new SelectListItem() { Text= "Australia", Value = "2"}
                },"Value","Text");
            }
            return View(model);
        }

 

Add the view for the above action method and write the following code in it.

View
@model MVCControls.Models.CountryModel
@{
    ViewBag.Title = "Index";
}
<h2>Dropdownlist Validation</h2>
@using (Html.BeginForm())
{
    @Html.ValidationSummary()
    @Html.Label("Country")
    @Html.DropDownListFor(c => c.SelectedCountryId,Model.Countries, "..Select..")
    @Html.ValidationMessage("Country is required.");
    <input type="submit" name="name" value="Submit" />
}

Now rebuild the application and Run

image

image

image

Simple Dropdownlist in MVC 5 with SelectList in Model


In this post we will learn how to implement simple Dropdown list with model binding and selectlist in MVC 5.

Let’s create Model as follows

Model:

Country Model
public class Country
{
    public int SelectedCountryId { get; set; }
    public System.Web.Mvc.SelectList Countries { get; set; }
}

 

Now add a controller and add the following action method in it

Action Mehtod
public ActionResult Index1(Country model)
{
    model.Countries = this.GetCountries();
    return View(model);
}

 

GetCountries Method:

GetCountries Method
[NonAction]
private SelectList GetCountries()
{
    return new SelectList(new List<SelectListItem>{
          new SelectListItem { Selected = true, Text = "–Select Country–", Value = "0"},
          new SelectListItem { Selected = false, Text = "India", Value = "1"},
        new SelectListItem {Selected = false, Text = "USA", Value = "2"},
        new SelectListItem{ Selected = false,Text = "UK", Value = "3"},
    }, "Value", "Text", "0");
}

Now add the view and write the following code:

View:

View
@model WebApplication5.Models.Country
@{
    ViewBag.Title = "Index1";
}

<h2>Dropdownlist with SelectList and model binding</h2>

@using (Html.BeginForm())
{
    if (Model.Countries != null)
    {
        @Html.Label("County: ")
        @Html.DropDownListFor(m => m.SelectedCountryId, Model.Countries)<br />
    }
    <input type="submit" name="name" value="Submit" /><br />
    if (Model.SelectedCountryId > 0)
    {
        @Html.Label("Selected Country : ")
        @Html.Label(Model.Countries.Where(c => c.Value == Model.SelectedCountryId.ToString()).Select(c => c.Text).FirstOrDefault())
    }
}

 

Now rebuild the application and run

image

image