Collection Binding in ASP.NET MVC3 with AJAX

There is a less-common scenario in web applications where we need to edit collection of objects and submit the whole back to the system. For example, let us take the below view model:

public class FruitModel...
        public string Name { get; set; }
        public bool IsFresh { get; set; }
        public bool IsPacked { get; set; }
                public decimal UnitPrice { get; set; }

The UI for this scenario is shown below:

Leave the top and bottom “Lorem ipsum” text, these are just gap fillers.  The user can change the “IsFresh” and “IsPacked” settings of the fruits and the unit prices.

Challenge

This post addresses the following simple problems when using ASP.NET MVC3:

  • Sending back collection of data to a MVC action
  • Also send back additional parameter(s) to the same MVC action
  • Sending back read-only data
  • By Ajax

Solution

When the user hitting this site, the HomeController’s Index will be called:
public ActionResult Index()...
        List collection = new List()
        {
                new FruitModel {Name = "Apple", IsFresh=true, IsPacked=false, UnitPrice = 10M},
                new FruitModel {Name = "Orange", IsFresh=false, IsPacked=false, UnitPrice = 5M},
                new FruitModel {Name = "Strawberry", IsFresh=true, IsPacked=true, UnitPrice = 15M}
        };
        ViewBag.NetAmount = IncludeTax(collection.Sum(fm => fm.UnitPrice));
        ViewBag.ShopId = Guid.NewGuid();
        return View(collection);
In the Index view, I’ve used NetAmount value of ViewBag as shown below:

Welcome to Fruit Shop

Lorem ipsum...
@Html.Partial("_Fruit", (List)Model)
Net Amount: @ViewBag.NetAmount
Lorem ipsum...
The main part of the Fruit Shop is defined in _Fruit partial view.  It requires the FruitModel collection and shop ID (in ViewBag).
Simply passing the Model in @Html.Partial(…) will throw the error “‘System.Web.Mvc.HtmlHelper’ has no applicable method named ‘Partial’ but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.”.  So, cast it to appropriate type, here List.
The partial view _Fruit is
@model List

@using (Ajax.BeginForm(new AjaxOptions
        {
            HttpMethod = "Post",
            UpdateTargetId = "netAmountDiv"
        }
))
{



@for (int i = 0; i < Model.Count; i++)
{
    
}

Name IsFresh IsPacked Unit Price
@Html.DisplayFor(modelItem => Model[i].Name) @Html.HiddenFor(modelItem => Model[i].Name) @Html.EditorFor(modelItem => Model[i].IsFresh) @Html.EditorFor(modelItem => Model[i].IsPacked) @Html.EditorFor(modelItem => Model[i].UnitPrice)
}
Now the important point here is, when you want to post back collection of FruitModel, the naming pattern of every HTML item in the collection should be “obj-name[index].property-name”.  For example, for the above code, ASP.NET generates HTML for an item like below:

        Apple
        


        


        


        
This HTML code actually generate a post back collection as shown below when submitting the form.
submitFruit=Change&[0].Name=Apple&[0].IsFresh=true&[0].IsFresh=false&[0].IsPacked=false&
[0].UnitPrice=10.00&[1].Name=Orange&[1].IsFresh=false&[1].IsPacked=true&[1].IsPacked=false&
[1].UnitPrice=5.00&[2].Name=Strawberry&[2].IsFresh=true&[2].IsFresh=false&[2].IsPacked=true&
[2].IsPacked=false&[2].UnitPrice=25&shopId=c9517c6b-c911-4a28-9a0a-3e47ccb60bd8&X-Requested-With=XMLHttpRequest
The above data matched with List model and with the other parameter name too.  The additional parameter I’m passing is “shopId” hidden value which is received from ViewBag.ShopId.  The main changes I did in the above code are:
  • Used List for @model instead of IEnumerable, hence I can use Count property.
  • Used for i = 0…List.Count instead of foreach.
ASP.NET MVC3 uses “name.propertyname” pattern, if you use “foreach”.  This wouldn’t send back the collection to the server.  Now, let us see the Index action for POST:
[HttpPost]
public ActionResult Index(Guid shopId, List collection)...
        decimal addlTax = 0M;
        if (collection.Any(fm => fm.UnitPrice > 200)) addlTax += 2M;
        return Content("Net Amount: " + IncludeTax(collection.Sum(fm => fm.UnitPrice) + addlTax).ToString());
Leave the tax calculation stuff, it is just for making some difference from GET Index().  The above method send back the tax calculation as plain text to the client.  This is the place for AJAX.  This can be achieved by Ajax.BeginForm() in the above code, where I’ve mentioned that the result should be placed on an element with id “netAmountDiv”.  So, we can get the result asynchronously.  To make this AJAX.BeginForm() to work, you have to:
  • include jQuery’s unobtrusive AJAX script (jquery.unobtrusive-AJAX.min.js)
  • add “” option in appsetting section of web.config

Also, note that to send read-only item as part of the collection, in the above example FruitModel.Name, use hidden input control also.

Mark this!
  • Digg
  • del.icio.us
  • Add to favorites
  • RSS