ASP.NET and More

Learning ASP.NET MVC currently

Bulk Data Update with ASP.NET MVC

Recently I was doing some R&D with ASP.NET MVC. During that I was mimicking the Create a Movie Database Application in 15 Minutes with ASP.NET MVC (C#) tutorial, which is a nice ice-breaker tutorial. Once I was done with it, I was thinking of some more complex real-life scenarios. As a business application developer, I came across a scenario when I need to implement a bulk update operation through a Web interface. I hate it simply !!!!! Binding the data, then iterate through the Grid, do a lot of FindControl….

So I thought let’s try the same scenario with ASP.NET MVC….

There is a nice blog by Phil Haack on the topic, which is for Beta version, and the same approach  doesn’t quite work with the released version. After tumbling few times finally I got the thing working, and my first observation is that, I am loving it !!!!!, it’s short, much more simple and the best part no more auto generated garbage HTML markups. The result is much more cleaner in terms of HTML. Though some you may not agree with me, but I always thought of having greater control over the HTML generation, the way it was with Classic ASP. Webforms doesn’t provide that, specially if you are using a Gridview.

So let’s look at the page.

Home Screen

 

It’s a simple UI, where I can update multiple book records, and then hit the “Save Changes” button to commit all the changes.

First I have created a database with a simple table, and the generated the ASP.NET Entity class, to perform the CRUD operation, though in this example i will only use the Update operation. I am not going into details on How to use the Entity framework.

I have used the HomeController’s Index() method to create a View with all the Movie records, in a tabular format. The code looks like,

   1: BookStoreEntities _db = new BookStoreEntities();
   2:     public ActionResult Index()
   3:     {
   4:         return View(_db.BookDetails.ToList());
   5:     }

The View looks like this:

<form action="/Home/Index" method="post">
 <table>
     <tr>
         <th>
             BookID
         </th>
         <th>
             Title
         </th>
         <th>
             Author
         </th>
         <th>
             Publication
         </th>
     </tr>
 <% int i = 0; %>
 <% foreach (var item in Model) { %>
 
     <tr>
         <td>
             <%= Html.Encode(item.BookID) %>
             <input type="hidden" name='<%= "BookList[" + i + "].BookID" %>' value='<%=item.BookID %>' />
         </td>
         <td>
             <input type="text" name='<%= "BookList[" + i + "].Title" %>' value='<%=item.Title %>' />
         </td>
         <td>
             <input type="text" name='<%= "BookList[" + i + "].Author" %>' value='<%=item.Author %>' />
         </td>
         <td>
             <input type="text" name='<%= "BookList[" + i + "].Publication" %>' value='<%=item.Publication %>' />
         </td>
     </tr>
 <% i++; %>
 <% } %>
 
 </table>
 
 <p>
     <input type="submit" value="Save Changes" />
 </p>
 </form>

The View is simple enough, though there are few important points here, without which the Save won’t work. First of all I have added a <form> tag, with method=”post”, and action="/Home/Index".  Now the most important point, name='<%= "BookList[" + i + "].BookID" %>' , here i is a Zero-based index, which will be used to recreate the List of books upon submission.

Next I have added another Index method to handle the Form submission.

   1: [AcceptVerbs(HttpVerbs.Post)]
   2:        public ActionResult Index(IList<BookDetails> BookList)
   3:        {
   4:            if (ModelState.IsValid)
   5:            {
   6:                foreach (BookDetails editedBook in BookList)
   7:                {
   8:                    var tempBook = (from book in _db.BookDetails
   9:                                    where book.BookID == editedBook.BookID
  10:                                    select book).First();
  11:  
  12:                    _db.ApplyPropertyChanges(tempBook.EntityKey.EntitySetName, editedBook);
  13:                }
  14:                _db.SaveChanges();
  15:                return View(_db.BookDetails.ToList());
  16:            }
  17:            else
  18:            {
  19:                return View();
  20:            }
  21:        }

Also note that the name “BookList” is same as in the HomeController’s Index method’s parameter’s name.

I guess that’s it!!!! very simple and clean way to handle Bulk Update scenario.

Source Code

Comments

progg.ru said:

Thank you for submitting this cool story - Trackback from progg.ru

# June 18, 2009 11:02 AM

DotNetShoutout said:

Thank you for submitting this cool story - Trackback from DotNetShoutout

# June 18, 2009 5:03 PM

Alex said:

Thanks. It's very useful article!

I have a question: How to add validation to the textbox for this bind method?

# July 22, 2009 5:55 AM

bhaskar_412 said:

Alex:

Let's say the list in your controller is "UpdatedList" and the textbox you want to validate is someting like <%= Html.TextBox("UpdatedList[" + i + "].Title",item.Title) %>. So in the ModelState you need to add the Validation error message with the same "Key" as the control, in this case your validation control would be something like : <%= Html.ValidationMessage("UpdatedList[" + i + "].Title")%>

Also in the controller or you would do something like: ModelState.AddModelError("UpdatedList[" + i + "].Title", "Error Message"), where i is the counter.

Hope it answers your question.

# July 22, 2009 7:13 AM

mohammed askar said:

Simple and cool

# March 8, 2010 2:12 AM

Giancarlo said:

Hi,

I just tired your method in MVC 2 but it's not working quite right, I was wondering if you could help. What I'm doing is making some fields editable but others not. Now when I post back and look through the controller code in debug mode, the identifier for each object of the IList<Objects> shows up, but the field that I had a textbox input shows the original value not the value that I entered in the textbox. I appreciate it if you could offer some advice on this.

Thanks,

Giancarlo

# May 24, 2010 12:47 PM

Giancarlo said:

figured it out, amazing what typos can do to your code. :P

# May 24, 2010 3:19 PM

Jonas said:

@Giancarlo

Do you have example code for mvc2, or do the same as this work?

Best regards,

Jonas

# June 10, 2010 6:25 AM

Nils said:

This has been extremely helpful, thank you!

Steve Sanderson also posted a similar example based on ASP.NET MVC 2:

blog.stevensanderson.com/.../editing-a-variable-length-list-aspnet-mvc-2-style

# June 11, 2010 2:11 PM

ASP.Net MVC – Update Multiple Records at Once « Brad's Blog said:

Pingback from  ASP.Net MVC &#8211; Update Multiple Records at Once &laquo; Brad&#039;s Blog

# December 10, 2010 11:15 PM

Dominique said:

This is helpful but what would be more helpful is to show how to add dropdown list and calendars bound to a row in a table

# December 7, 2011 3:43 AM

Stephen said:

This is exactly what I was looking for. Why the standard  MVC grids can't incorporate this feature is beyond me.

# February 8, 2012 4:09 AM

ASVTech said:

Thank you very much!!!. I've been looking for this for 2-3 weeks. Very nice article.

# March 5, 2012 3:35 AM

mike said:

Thanks lot.

# April 9, 2012 2:00 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)