A Place to Learn Ur-self…


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


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

Here I am going to implement nested 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


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


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


In this post we will learn How to implement Checkbox list in mvc 5 with model

Model:

First create Model as follows

Player Model
public class Player
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public bool IsSelected { get; set; }
    }

Now let’s create action method in controller class

Action Method for checkboxlist
public ActionResult cbxList(IEnumerable<Player> model)
        {
            IEnumerable<Player> palyers = new List<Player>() {
                new Player(){Id = 1, Name = "Venki"},
                new Player(){Id = 2, Name = "Karthikeya"},
                new Player(){Id = 3, Name = "Ravi"},
                new Player(){Id = 4, Name = "Prasad"},
                new Player(){Id = 5, Name = "Hari"}
            };
            if (model == null)
                model = palyers;
            return View(model);
        }

Now lets create Editor Template for the player model as follows:

first create a folder with name “EditorTemplates” under Views folder for your controller

Write the following code in that Editor Template

Editor Template
@model MVCControls.Models.Player

@{
    ViewBag.Title = "Player";
}

@Html.HiddenFor(p => p.Id)
@Html.HiddenFor(p => p.Name)
@Html.CheckBoxFor(p=>p.IsSelected)
@Html.DisplayFor(p => p.Name)

Now create a view for the current action method

View for the actionmethod
@model IEnumerable<MVCControls.Models.Player>
@{
    ViewBag.Title = "cbxList";
}

<h2>Checkbox lsit in MVC 5</h2>

@using (Html.BeginForm())
{
    @Html.EditorForModel()
    <br />
    <input type="submit" value="Submit" />
    if (Model.Count(n => n.IsSelected) > 0)
    {
        <br />
        @Html.Label("Selected Players are:")<br />
        foreach (var item in Model.Where(n => n.IsSelected))
        {
            @Html.Label(item.Name)<br />
        }
    }
}

Now Rebuild the application and Run.

image

image


In this post we will learn how to implement Radiobutton list control with enum in mvc 5

Let’s sart by creating Enum for favourite subjects

Enum:

public enum FavouriteSubject
    {
        CSharp = 0,
        Aspnet = 1,
        SqlServer = 2,
        Sharepoint = 3
    }

next prepare model as follows

Model:

public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public FavouriteSubject FavSubject { get; set; }
    }

 

Controller:

lets create action method in controller as follows.

public ActionResult rdbtnListWithEnum(Student model)
        {
            return View(model);
        }

 

View:

We can implement view in different ways

Method 1: Radiobutton list with foreach loop

@model MVCControls.Models.Student
@using MVCControls.Models;
@{
    ViewBag.Title = "Radio Button List with enum and model || Chikkanti.Wordpress.com";
}

<h2>Radiobutton list with enum and model</h2>

@using (Html.BeginForm())
{
    foreach (var favsub in Enum.GetValues(typeof(FavouriteSubject)))
    {
        var id = TagBuilder.CreateSanitizedId(string.Format("{0}_{1}_{2}", "rdbtn", typeof(FavouriteSubject), favsub));
        <div>
            @Html.RadioButtonFor(s => s.FavSubject, favsub, new { id })
            @Html.Label(favsub.ToString(), new { @for = id })
        </div>
    }
    <input type="submit" name="name" value="Submit" />
    <br />
    @Html.Label("Your selected option: " + Model.FavSubject)
}

Method 2: Simple Radiobutton list

@model MVCControls.Models.Student
@using MVCControls.Models;
@{
    ViewBag.Title = "Radio Button List with enum and model || Chikkanti.Wordpress.com";
}

<h2>Radiobutton list with enum and model</h2>

@using (Html.BeginForm())
{
    @Html.RadioButtonFor(s => s.FavSubject, FavouriteSubject.CSharp)@Html.Label("CSharp")<br />
    @Html.RadioButtonFor(s => s.FavSubject, FavouriteSubject.Aspnet)@Html.Label("Aspnet")<br />
    @Html.RadioButtonFor(s => s.FavSubject, FavouriteSubject.SqlServer)@Html.Label("SqlServer")<br />
    @Html.RadioButtonFor(s => s.FavSubject, FavouriteSubject.Sharepoint)@Html.Label("Sharepoint")<br />
    <input type="submit" name="name" value="Submit" />
    <br />
    @Html.Label("Your selected option: " + Model.FavSubject)
}

Now rebuild the project and run

image

image


In this post we will learn How to implement Radiobutton list with list in foreach loop in mvc 5 with model using html helper radiobuttonlistfor

Model:

First add models as follows

public class Country
    {
        public int CountryId { get; set; }
        public List<City> Cities { get; set; }
        public int SelectedCityId { get; set; }
        public string SelectedCityName
        {
            get
            {
                if (this.Cities != null && this.SelectedCityId > 0)
                {
                    return Cities.Where(n => n.Id == this.SelectedCityId).Select(s => s.CityName).FirstOrDefault();
                }
                else
                {
                    return string.Empty;
                }
            }
        }
    }
    public class City
    {
        public int Id { get; set; }
        public string CityName { get; set; }
    }

Controller:

Add a controller and a action method in it as follows

public ActionResult rdbtnListWithForeach(Country model)
        {
            List<City> cities = new List<City>() {
                new City(){Id = 1, CityName="Hyderabad"},
                new City(){Id = 2, CityName="Ongole"},
                new City(){Id = 3, CityName="Guntur"},
                new City(){Id = 4, CityName="Vijayawada"}
            };
            model.Cities = cities;
            return View(model);
        }

View:

@model MVCControls.Models.Country
@{
    ViewBag.Title = "Radiobutton List inside foreach in MVC 5 using model || Chikkanti.Wordpress.com";
}

<h2>Radiobutton List inside foreach in MVC 5</h2>

@using (Html.BeginForm())
{
    foreach (var city in Model.Cities)
    {
        @Html.RadioButtonFor(g => g.SelectedCityId, city.Id)@Html.Label(city.CityName)
        <br />
    }
    <br />
    <input type="submit" value="Submit" /><br />
    if (!string.IsNullOrEmpty(Model.SelectedCityName))
    {
        @Html.Label("Your selected city is: " + Model.SelectedCityName);
    }
}

Now Rebuild the application and run.

Output:

image

image

image