Binding and Posting a Collection of Custom types in ASP.NET MVC.

In ASP.NET MVC we can simply bind and post a custom type of collection. Here I am demonstrating a sample application for implementing this.
Create a sample class of type Person
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}

Create a controller with two action such as Index for loading a List and Register for posting List
public class PersonController : Controller
{
public ActionResult Index()
{
var persons = new List()
{
new Person {FirstName = "Jameel", LastName = "VM"},
new Person {FirstName = "Jasin", LastName = "VM"}
};
return View(persons);
}
[HttpPost]
public ViewResult Register(List persons )
{
return View();
}
}
}

Index view code for looping the person collection and also I had put a form tag which map to Register action for posting the edited collection

code

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

When we click the register button the form will post the collection of values to Register action like below

1

2

Loading DropdownList in ASP.NET MVC

In ASP.NET MVC you can load DropDownList easily. There are different ways for loading this. Here I am demonstrating a simple example for loading some countries.
Create a Generic class DropDownList<T> which contain a method LoadItems which return Sytem.Web.Mvc.SelectList
public static class DropDownList<T>
{
public static SelectList LoadItems(IList<T> collection, string value, string text)
{
return new SelectList(collection, value, text);
}
}

Create two class such as Country and a CountryViewModel which containĀ  a property for getting PostedCountryId
public class CountryViewModel
{
public int PostedCountryId { get; set; }
}
public class Country
{
public int Id { get; set; }
public string Name { get; set; }
}

Then I am going to fill the countries list in to a ViewData. You can also use ViewBag instead
public class DropDownController : Controller
{
public ActionResult Index()
{
ViewData["LoadCountries"] = DropDownList<Country>.LoadItems(CountriesCollection(), "Id", "Name");
return View();
}
public List<Country> CountriesCollection()
{
var list = new List<Country>
{
new Country{Id = 1,Name = "India"},
new Country{Id = 2,Name = "Brazil"},
new Country{Id = 1,Name = "Gautemala"},
new Country { Id = 1,Name = "Spain"}
};
return list;
}
}

From the view you can retrieve the ViewData value to DropDownListFor helper
@model MVCCollection.Controllers.CountryViewModel
@using (Html.BeginForm("Create", "DropDown", FormMethod.Post))
{
@Html.DropDownListFor(model => model.PostedCountryId, (IEnumerable<SelectListItem>) ViewData["LoadCountries"], "--Select--", new {@class = "select"})
<input type="submit" value="PostSelectedCountryId"/>
}

When you call the submit button you will get selected country id to CountryViewModel class like below
1

Enjoy coding…