Asp.net,C#.net,MVC,SQL Server,Javascript,Jquery


Some times we just need to save/export C# object to XML file.

So let’s see how to do that.

Creating C# Object

First we need to create C# class as follows

Employee Class
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Dept { get; set; }
}

Next we have to create object of the above class and fill it with data as follows

Employee Object with data
List<Employee> emps = new List<Employee>();
emps.Add(new Employee { Id = 1, Name = “Venki Chikkanti”, Dept = “Development” });
emps.Add(new Employee { Id = 1, Name = “Matt”, Dept = “Management” });
emps.Add(new Employee { Id = 1, Name = “Mark”, Dept = “Transport” });

Now let’s serialize this data and store into xml file as follows.

Save to XML file
System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(typeof(List<Employee>));

var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + “//XMLData.xml”;
System.IO.FileStream file = System.IO.File.Create(path);

writer.Serialize(file, emps);
file.Close();

So the file will be saved to MyDocuments folder with filename as XMLData.

Output File content:

XML File
<?xml version=1.0?>
<ArrayOfEmployee xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xmlns:xsd=http://www.w3.org/2001/XMLSchema>
<Employee>
<Id>1</Id>
<Name>Venki Chikkanti</Name>
<Dept>Development</Dept>
</Employee>
<Employee>
<Id>1</Id>
<Name>Matt</Name>
<Dept>Management</Dept>
</Employee>
<Employee>
<Id>1</Id>
<Name>Mark</Name>
<Dept>Transport</Dept>
</Employee>
</ArrayOfEmployee>

tOtAL cOdE:

Total Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleWorks
{
public class CSharpObjToXMLFile
{
static void Main(string[] args)
{
List<Employee> emps = new List<Employee>();
emps.Add(new Employee { Id = 1, Name = “Venki Chikkanti”, Dept = “Development” });
emps.Add(new Employee { Id = 1, Name = “Matt”, Dept = “Management” });
emps.Add(new Employee { Id = 1, Name = “Mark”, Dept = “Transport” });

System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(typeof(List<Employee>));

var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + “//XMLData.xml”;
System.IO.FileStream file = System.IO.File.Create(path);

writer.Serialize(file, emps);
file.Close();
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Dept { get; set; }
}
}
}


In this post we will learn how to render partial view to string using razor view engine in mvc.

In some cases we need to render our view or partial view to string and return as string then we will use it to render inside any containers.

Example 1: To send e-mail with HTML content.

Example 2: To send HTML data in string from the API’s or as service response

Example 3: To update the user with customized alerts.

Example 4: To update the page with ajax calls

So it is important to learn how to render view or partial view to string.

First we need to prepare partial view with data, for this we need to prepare some data object as follows:

Product
public class Products
{
public List<Product> GetProducts()
{
return new List<Product>()
{
new Product{ Id=1,Name=“F&D E200 (2.0 Channel)”,Price=849,Description=“F&D’s E200 is an ergonomically designed sound bar which can conveniently get attached to your laptop or PC. You may place it in your purse and carry it to work without any excess weight or bulk.”,ImagePath=“/Content/Images/1.jpeg”},
new Product{ Id=2,Name=“F&D F203G Laptop Speakers (2.1 Channel)”,Price=1289,Description=“2.1 Channel Configuration,Subwoofer,Satellites,Wood Chassis”,ImagePath=“/Content/Images/2.jpeg”},
//new Product{ Id=3,Name=”Zebronics ZEB-S310 Club Wired Laptop Speakers (Black, 2…”,Price=199,Description=”Interface : usb, power input : (dc) 5v, frequency response : 20hz~20khz, driver unit : 2.5 x 2, output power : 3w x 2 (rms), s/n ratio : ?75 db, separation : ?65 db, impedance : 4 ?, dimensions : 70 x 70 x 187mm (wxhxd), input connectivity : 3.5 mm jack.”,ImagePath=”/Content/Images/3.jpeg”},
new Product{ Id=4,Name=“Portronics Pure Sound Portable Speaker (2.0 Channel)”,Price=1165,Description=“8 hrs Battery Life,Satellites”,ImagePath=“/Content/Images/4.jpeg”},
new Product{ Id=5,Name=“Philips DSP 2800 Home Audio (5.1 Channel)”,Price=2980,Description=“2.1 Channel Configuration,Subwoofer,Satellites,Wood Chassis”,ImagePath=“/Content/Images/5.jpeg”},
//new Product{ Id=6,Name=”Intex IT-880 s Wired Laptop Speakers (Black, 2.1 Channel)”,Price=675,Description=”2.1 Channel Stereo,Subwoofer,Speaker,Headphone Socket”,ImagePath=”/Content/Images/6.jpeg”},
new Product{ Id=7,Name=“JBL Charge Speaker (Single Unit Channel)”,Price=6749,Description=“20 W RMS Output Power,5.1 Home Audio,inch Woofer,inch Full Range,High Gloss Finish”,ImagePath=“/Content/Images/7.jpeg”},
new Product{ Id=8,Name=“Intex IT-880 S OS Wired Laptop Speakers (Black, 2.1 Cha…”,Price=649,Description=“150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device”,ImagePath=“/Content/Images/8.jpeg”},
new Product{ Id=9,Name=“Quantum QHM611 Wired Laptop Speakers (Black, 2.0 Channel)”,Price=125,Description=“150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device”,ImagePath=“/Content/Images/9.jpeg”},
new Product{ Id=10,Name=“Lenovo Portable Speaker M0520 (2.0 Channel)”,Price=812,Description=“150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device”,ImagePath=“/Content/Images/10.jpeg”}
};
}
}

Then add a partial view in shared folder as follows:

_ProductBox partial view
@model IEnumerable<MVCControls.Models.Product>

@foreach (var product in Model)
{
<div style=”width: 200px; height: 250px; border: 1px #ffd926 solid; padding: 15px; float: left; overflow: hidden; overflow-wrap: break-word; overflow-y: hidden; “>
<div>
<img src=”@product.ImagePath alt=”@product.Name />
</div>
<div style=”font-weight:bold;“>
<strong>@Html.Label(“Name”):</strong> @product.Name
</div>
<div style=”color:green;“>
<strong>@Html.Label(“Price”):</strong> @product.Price
</div>
<div style=”color:brown;“>
<strong>@Html.Label(“Description”):</strong> @product.Description
</div>
</div>
}

then add an action method in controller

Action Method
public ActionResult RenderPartialViewToString()
{
string result = string.Empty;
//get view name from controller context
//var viewName = this.ControllerContext.RouteData.GetRequiredString(“action”);
//get view name directly
var viewName = “_ProductBox”;
ViewData.Model = new Products().GetProducts();
using (var sw = new System.IO.StringWriter())
{
ViewEngineResult viewResult = System.Web.Mvc.ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
var viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
viewResult.View.Render(viewContext, sw);
result = sw.GetStringBuilder().ToString();
}
return View(new ProductCatalog() { Catalog = result });
}

Then add view for this action method

View
@model MVCControls.Models.ProductCatalog
@{
Layout = null;
}<!DOCTYPE html>

<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>RenderPartialViewToString</title>
</head>
<body>
<div>
<div style=”padding: 5px;width:850px;margin:0px auto;“>
@Html.Raw(Model.Catalog)
</div>
</div>
</body>
</html>

Now rebuild the application and run

Output:

image


Q: What is partial view?

Ans: A partial view is a customized shared view, which can’t be served directly and can be used in other views. i.e Reusable custom view.

Q: What are the advantages with partial views?

Ans: 1. Sometimes you need to return just a piece and you can do it by a async request (using ajax). In these cases, you use an action that returns a Partial View.

2. Sometimes you need to implement an View that need to add a piece of code, so, you can render it using a Partial View.

3. Using partial views you can avoid code redundancy, i.e partial view are reusable

Q: How to Implement partial view in MVC

Ans: Here we will learn how to implement partial view in mvc with product catalog example.

let’s create product catalog data first

To reate product catalog data first create model as follows

Product Model
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Description { get; set; }
    public string ImagePath { get; set; }
}

Now create product catalog data

Products
public class Products
    {
        public List<Product> GetProducts()
        {
            return new List<Product>()
            {
                new Product{ Id=1,Name="F&D E200 (2.0 Channel)",Price=849,Description="F&D's E200 is an ergonomically designed sound bar which can conveniently get attached to your laptop or PC. You may place it in your purse and carry it to work without any excess weight or bulk.",ImagePath="/Content/Images/1.jpeg"},
                new Product{ Id=2,Name="F&D F203G Laptop Speakers (2.1 Channel)",Price=1289,Description="2.1 Channel Configuration,Subwoofer,Satellites,Wood Chassis",ImagePath="/Content/Images/2.jpeg"},
                //new Product{ Id=3,Name="Zebronics ZEB-S310 Club Wired Laptop Speakers (Black, 2…",Price=199,Description="Interface : usb, power input : (dc) 5v, frequency response : 20hz~20khz, driver unit : 2.5 x 2, output power : 3w x 2 (rms), s/n ratio : ?75 db, separation : ?65 db, impedance : 4 ?, dimensions : 70 x 70 x 187mm (wxhxd), input connectivity : 3.5 mm jack.",ImagePath="/Content/Images/3.jpeg"},
                new Product{ Id=4,Name="Portronics Pure Sound Portable Speaker (2.0 Channel)",Price=1165,Description="8 hrs Battery Life,Satellites",ImagePath="/Content/Images/4.jpeg"},
                new Product{ Id=5,Name="Philips DSP 2800 Home Audio (5.1 Channel)",Price=2980,Description="2.1 Channel Configuration,Subwoofer,Satellites,Wood Chassis",ImagePath="/Content/Images/5.jpeg"},
                //new Product{ Id=6,Name="Intex IT-880 s Wired Laptop Speakers (Black, 2.1 Channel)",Price=675,Description="2.1 Channel Stereo,Subwoofer,Speaker,Headphone Socket",ImagePath="/Content/Images/6.jpeg"},
                new Product{ Id=7,Name="JBL Charge Speaker (Single Unit Channel)",Price=6749,Description="20 W RMS Output Power,5.1 Home Audio,inch Woofer,inch Full Range,High Gloss Finish",ImagePath="/Content/Images/7.jpeg"},
                new Product{ Id=8,Name="Intex IT-880 S OS Wired Laptop Speakers (Black, 2.1 Cha…",Price=649,Description="150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device",ImagePath="/Content/Images/8.jpeg"},
                new Product{ Id=9,Name="Quantum QHM611 Wired Laptop Speakers (Black, 2.0 Channel)",Price=125,Description="150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device",ImagePath="/Content/Images/9.jpeg"},
                new Product{ Id=10,Name="Lenovo Portable Speaker M0520 (2.0 Channel)",Price=812,Description="150 – 20000 Hz Frequency Range, Bluetooth Streaming, 6000 mAh Lithium-ion Rechargeable Battery, Bluetooth Speaker, 12 hrs Playback Time, LED Indicator, Recharge Mobile Device",ImagePath="/Content/Images/10.jpeg"}
            };
        }
    }

Now create one action method in controller as follows

Action Method
//
// GET: /PartialViews/
public ActionResult Index()
{
    Products products = new Products();
    return View(products.GetProducts());
}

 

Now add a view for the above action as follows

Right click on the action method and choose addview…

image

image

Click add to create view.

Write the following code in the created view

Product Catalog view
@model IEnumerable<MVCControls.Models.Product>
@{
    ViewBag.Title = "Partial views in MVC 5 || Chikkanti.wordpress.com";
    Layout = null;
}

<div style="padding: 5px;width:850px;margin:0px auto;">
    <h2>Partial views in MVC 5</h2>
    @foreach (var product in Model)
    {
        @Html.Partial("_ProductBox", product)
    }
</div>

 

In the above code @html.Partial is a helper class and we can use this to render our partial view. For this helper we are passing two parameters

1.”_ProductBox”: partial view name

2.product : Model for the partial view

Now let’s add the partial view in shared folder under views as follows

RightClick on Shared folder under views and choose add then view and fill the following details

image

image

After adding this partial view write the following code into it.

Partial View
@model MVCControls.Models.Product
<div class="products">
    <div>
        @Html.HiddenFor(m => m.Id)
    </div>
    <div>
        <img src="@Model.ImagePath" alt="@Model.Name" />
    </div>
    <div style="font-weight:bold;">
        @Html.LabelFor(m => m.Name):@Html.DisplayFor(m => m.Name)
    </div>
    <div style="color:green;">
        @Html.LabelFor(m => m.Price):RS.@Html.DisplayFor(m => m.Price)
    </div>
    <div style="color:brown;">
        @Html.LabelFor(m => m.Description):@Html.DisplayFor(m => m.Description)
    </div>
</div>
<style>
    .products {
        width: 150px;
        height: 200px;
        border: 1px #ffd926 solid;
        padding: 15px;
        float: left;
        overflow: hidden;
        overflow-wrap: break-word;
        overflow-y: hidden;
    }
</style>

 

Now Rebuild the application and run

image


In this post we will learn how to upload multiple files at a time using multi fileupload in MVC 5 & razor

Add one controller and write the following code in it

Action Method
//
// GET: /Multi Fileupload/
//
public ActionResult Index()
{
return View();
}
//
// POST: /Multi Fileupload/
//
[HttpPost]
public ActionResult Index(ICollection<HttpPostedFileBase> fu_files)
{
var directory = Server.MapPath(“~/Content/Uploads/”);
foreach (HttpPostedFileBase file in fu_files)
{
if (file != null && file.ContentLength > 0)
{
Stream fs = file.InputStream;
int size = file.ContentLength;
byte[] bytes = new byte[size];
fs.Read(bytes, 0, size);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
System.IO.File.WriteAllBytes(directory + file.FileName, bytes);
}
}
Dictionary<string, string> UploadedImages = new Dictionary<string, string>();
foreach (var item in Directory.EnumerateFileSystemEntries(directory))
{
string[] str = item.Split(new char[] { ‘\\’ }, StringSplitOptions.RemoveEmptyEntries);
UploadedImages.Add(str[str.Length – 1], “/Content/Uploads/” + str[str.Length – 1]);
}
ViewBag.UploadedImages = UploadedImages;
return View();
}

Then add the view and write the following code

View
@{
ViewBag.Title = “Multi Fileupload in MVC || Chikkanti.wordpress.com”;
}<h2>Multi Fileupload in MVC</h2>

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = “multipart/form-data” }))
{
<table border=”1″ style=”border-color:black;background:#f5c9c9″>
<tr>
<td>
<input type=”file” name=”fu_files” multiple />
</td>
<td>
<input type=”submit” id=”resume” name=”name” value=”Submit” />
</td>
</tr>
@if (ViewBag.UploadedImages != null)
{
<tr>
<td><strong>Name</strong></td>
<td><strong>Image</strong></td>
</tr>
Dictionary<string, string> Images = ViewBag.UploadedImages as Dictionary<string, string>;
foreach (var Image in Images.Keys)
{
<tr>
<td>@Image</td>
<td><img src=’@Images[Image] height=”100px” width=”100px” /></td>
</tr>
}
}
else
{
<tr>
<td colspan=”2″><span>No files uploaded.</span></td>
</tr>
}
</table>
}

Rebuild the application and run

image

image

image

image


In this we will learn how to save files to server and display in mvc 5 using fileupload in rezor view engine.

First Create a Controller action method as follows

Action Method
//
// GET: /Fileupload/
//
public ActionResult Index()
{
    return View();
}
//
// POST: /Fileupload/
//
[HttpPost]
public ActionResult Index(HttpPostedFileBase fu_file)
{
    var directory = Server.MapPath("~/Content/Uploads/");
    if (fu_file != null && fu_file.ContentLength > 0)
    {
        Stream fs = fu_file.InputStream;
        int size = fu_file.ContentLength;
        byte[] bytes = new byte[size];
        fs.Read(bytes, 0, size);
        if (!Directory.Exists(directory))
        {
            Directory.CreateDirectory(directory);
        }
        System.IO.File.WriteAllBytes(directory + fu_file.FileName, bytes);
    }
    Dictionary<string, string> UploadedImages = new Dictionary<string, string>();
    foreach (var item in Directory.EnumerateFileSystemEntries(directory))
    {
        string[] str = item.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
        UploadedImages.Add(str[str.Length – 1], "/Content/Uploads/" + str[str.Length – 1]);
    }
    ViewBag.UploadedImages = UploadedImages;
    return View();
}

Generate or add the view for the action and write the following code

View
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <table border="1" style="border-color:black;background:#f5c9c9">
        <tr>
            <td>
                <input type="file" name="fu_file" />
            </td>
            <td>
                <input type="submit" id="resume" name="name" value="Submit" />
            </td>
        </tr>
        @if (ViewBag.UploadedImages != null)
        {
            <tr>
                <td><strong>Name</strong></td>
                <td><strong>Image</strong></td>
            </tr>
            Dictionary<string, string> Images = ViewBag.UploadedImages as Dictionary<string, string>;
            foreach (var Image in Images.Keys)
            {
                <tr>
                    <td>@Image</td>
                    <td><img src='@Images[Image]' height="100px" width="100px" /></td>
                </tr>
            }
        }
        else
        {
            <tr>
                <td colspan="2"><span>No files uploaded.</span></td>
            </tr>
        }
    </table>
}

 

Rebuild the application and run

image

image

image

image


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 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