How to bind and get list of objects in ASP.NET MVC postback?
I love ASP.NET MVC and the ease and cleanliness that it offers makes it more adorable to me.
Recently, I was working on a project and was facing this situation where I wanted to bind the list of objects to the page and get the value of the list of modified or new objects of the list back to the server in postback.
This was quite challenging and after lots of patience I was able to figure out the intricacies of ASP.NET MVC with binding ILIST object to the ASP.NET MVC view and getting its value in postback.
An example of this scenario could be academic history of a student. Academic history will capture all the schools and colleges attended by a student. In our case, to make it simple I am considering collegeDetails object as the object containing college name and the year attended.
I have an object called as the coverobject that encapsulates all the objects of the view page. It includes the student name, age, year of birth and the list of college details. Also we have the action button value property field defined in the coverobject. Action button value property defines various actions that the postback needs to handle. Please note, I have all the submit buttons of the page assigned the same name.
CoverObject of the view page defines all the properties and logic grouped elements of the page encapsulated in one object.
In the controller, the important thing is how you define the cover object. Remember to make the properties of the coverobject with get and set properties otherwise the values won't be assigned to it in postback.
In the view page, the important thing to look for is the naming convention of the controls. The name of the control maps to the model state object name. For the naming convention of the IList we need to have the index defined for each object in the list and the same index should be used for all the properties of that object.
Here is the sample of the controller of the page: using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcApplication18.Controllers;
namespace MvcApplication18.Controllers
{
public class CoverObject
{
public CoverObject()
{
List<string> years = new List<string>();
years.Add("1982");
years.Add("1983");
years.Add("1984");
ListOfYear = new SelectList(years);
ListOfCollegeDetails = new List<CollegeDetails>();
FormAction = string.Empty;
this.CollegeDetails = new CollegeDetails();
this.CollegeDetails.CollegeName = string.Empty;
this.CollegeDetails.Year = null;
}
public string Name { get; set; }
public int? Age { get; set; }
public int YearOfBirth { get; set; }
public SelectList ListOfYear { get; set; }
//List of college details
public List<CollegeDetails> ListOfCollegeDetails { get; set;}
//Used to determine different functions on the page
public string FormAction { get; set; }
//Used for Add New functionality
public CollegeDetails CollegeDetails { get; set; }
}
public class CollegeDetails
{
public string CollegeName { get; set; }
public int? Year { get; set; }
}
public class ListInAObjectController : Controller
{
public ActionResult Create()
{
CoverObject coverObject = new CoverObject();
coverObject.ListOfYear = new SelectList(coverObject.ListOfYear, "Text", "Text");
return View(coverObject);
}
// POST: /ListInAObject/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(CoverObject coverObject)
{
if (coverObject.FormAction.Equals("AddNewCollegeDetail"))
{
CoverObject coverObjectNew = new CoverObject();
coverObjectNew.ListOfCollegeDetails = coverObject.ListOfCollegeDetails;
coverObjectNew.Name = coverObject.Name;
coverObjectNew.Age = coverObject.Age;
coverObjectNew.YearOfBirth = coverObject.YearOfBirth;
coverObjectNew.ListOfYear = new SelectList(coverObjectNew.ListOfYear, "Text", "Text", coverObjectNew.YearOfBirth);
if (!string.IsNullOrEmpty(coverObject.CollegeDetails.CollegeName))
{
coverObjectNew.ListOfCollegeDetails.Add(coverObject.CollegeDetails);
}
return View(coverObjectNew);
}
//Perform someother action here
return View(coverObject);
}
}
}
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication18.Controllers.CoverObject>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Create</h2>
<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Fields</legend>
<p>
<label for="Name">Name:</label>
<%= Html.TextBox("coverObject.Name", Model.Name)%>
<%= Html.ValidationMessage("coverObject.Name", "*")%>
</p>
<p>
<label for="Age">Age:</label>
<%= Html.TextBox("coverObject.Age", Model.Age.ToString())%>
<%= Html.ValidationMessage("coverObject.Age", "*")%>
</p>
<p>
<label for="YearOfBirth">Year Of Birth:</label>
<%= Html.DropDownList("coverObject.YearOfBirth",Model.ListOfYear)%>
</p>
<fieldset><legend>List Of College Details:</legend>
<%int index = 0;
foreach (var item in Model.ListOfCollegeDetails)
{
%>
<input type="hidden" name="coverObject.ListOfCollegeDetails.Index" value="<%=index.ToString()%>" />
<input type="text" name="coverObject.ListOfCollegeDetails[<%=index.ToString() %>].CollegeName" value="<%=item.CollegeName %>" />
<input type="text" name="coverObject.ListOfCollegeDetails[<%=index.ToString() %>].Year" value="<%=item.Year %>" />
<%
index++;
} %>
Add
<p>
<input type="text" name="coverObject.CollegeDetails.CollegeName" value="<%=Model.CollegeDetails.CollegeName %>" />
<input type="text" name="coverObject.CollegeDetails.Year" value="<%=Model.CollegeDetails.Year %>" />
<input type="submit" name="coverObject.FormAction" value="AddNewCollegeDetail" />
</p>
</fieldset>
<p>
<input type="submit" name="coverObject.FormAction" value="Create" />
</p>
</fieldset>
<% } %>
<div>
<%=Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
After understanding the naming convention of the controls in the view of the page, it looks simple to bind Ilist in ASP.NET MVC postback.
Sample Application
Attached is a sample application to show how to bind and get list of objects in ASP.NET MVC postback.
Sample application can be found at:Sample application about how to bind and get list of objects in ASP.NET MVC
View the webcast at:Webcast of the sample application
View the webcast at:Webcast of the sample application
