ASP.Net MVC - How to Post a Collection

Here I will describe how to post a collection in ASP.Net MVC 3 using a sample application. The basic idea behind posting (passing HTML field values from view to controller) is by matching the name field of the rendered HTML control with receiving parameters in the Controller's action method.

Suppose I have a field in my Razor view as @Html.TextBox("myName","Fawas") inside a form tag, then while submitting the form I can receive the value "Fawas" from the variable "myName" in the action method of the Controller as in the following:

  1. [HttpPost]  
  2. public ActionResult ReceveMyName(string myName)  
  3. {  
  4. }  
So in the following section I will describe how to post a collection from the view to the controller by a sample application using MVC-3 razor view.

In the sample application we have the screen (Fig-1), where we can "Add" the status/comments in the text area. Once we "Add" the status, the same will be reflected in the down portion.

We have a "Save" button at the down that will save the entire collection to the database.

ASP.NETMVC1.jpg

Fig. 1

Here the content we are updating in text area is a "Tweet" model.

Tweet Model

  1. public class Tweet  
  2. {  
  3.     public Tweet()  
  4.     {  
  5.         Date = DateTime.UtcNow;  
  6.     }  
  7.     private DateTime date;  
  8.     public int Id { getset; }   
  9.     public string UserName { getset; }  
  10.     public string Text { getset; }        
  11.     public DateTime Date  
  12.     {  
  13.         get { return date.ToLocalTime(); }  
  14.         set { date = value; }  
  15.     }  
  16. } 

Once we add the comments we need to post the entire "Collection of Tweets" and "Tweet" to the controller action. In other words in Fig-1, textarea refers to a single Tweet by the user and the down shows the list of tweets provided by all the followers and the user.

View Model

So our view model will be as in the following:

  1. public class TwitterViewModel  
  2. {  
  3.     public Tweet Tweet { getset; }  
  4.     public IList<Tweet> Tweets { getset; }  
  5. } 

Views

Our main view is "Tweets.cshtml" as in the following and which will render another partial view "_Alltweets.cshtml" by passing the model.

Tweets.cshtml

  1. @model MongoTwitter.ViewModels.TwitterViewModel  
  2. @{  
  3.     ViewBag.Title = "Twitter";  
  4. }  
  5. <hgroup class="title">  
  6. <h2>What's happening</h2>  
  7. </hgroup>  
  8. <div style="width: 600px; border: 1px solid silver">  
  9.     @using (Ajax.BeginForm("AddTweet""Home"new AjaxOptions { UpdateTargetId = "AllTweets" }))  
  10.     {   
  11.         <div style="width: 600px; border-width: 1px">  
  12.             @Html.TextAreaFor(md => md.Tweet.Text)  
  13.             <input type="submit" value="Add" style="width: 70px; font-size: 12px" />  
  14.         </div>  
  15.         <div id="AllTweets">  
  16.             @Html.Partial("_AllTweets", Model)  
  17.         </div>  
  18.     }  
  19. </div>
_AllTweets.cshtml
  1. @model MongoTwitter.ViewModels.TwitterViewModel  
  2. @using (Html.BeginForm("SaveTweet""Home"))  
  3. {  
  4.     <div style="height: 300px; width: 600px; overflow-y: auto">  
  5.         <table border="1">  
  6.             @if (Model != null && Model.Tweets != null)  
  7.             {  
  8.                 for (int i = 0; i < Model.Tweets.Count; i++)  
  9.                 {  
  10.                  
  11.                 <tr style="vertical-align: top">  
  12.                     <td style="font-size: 12px; padding-left: 2px">  
  13.                         @Html.DisplayFor(modelItem => Model.Tweets[i].Date) -  
  14.                         @Html.DisplayFor(modelItem => Model.Tweets[i].UserName) :  
  15.                     </td>  
  16.                     <td>  
  17.                         @Html.Raw(Model.Tweets[i].Text.Replace("\r\n""<br />"))  
  18.                     </td>  
  19.                 </tr>  
  20.                 @Html.HiddenFor(modelItem => Model.Tweets[i].Id)   
  21.                 @Html.HiddenFor(modelItem => Model.Tweets[i].Date)   
  22.                 @Html.HiddenFor(modelItem => Model.Tweets[i].Text)   
  23.                 @Html.HiddenFor(modelItem => Model.Tweets[i].UserName)   
  24.                 }  
  25.             }  
  26.         </table>  
  27.     </div>  
  28.     <input type="submit" value="Save" style="float: right; width: 70px; font-size: 12px" />  
  29. }
The main things to note about "AllTweets.cshtml" is that, we have used a for loop to loop through all the items in the Tweets Collection for (int i = 0; i < Model.Tweets.Count; i++).
 
Here by using developer tools if we inspect the rendered HTML, we will see that the name field of the entire collection matches what needs to be posted for that collection, like Tweets[1].Id, Tweets[2].Id etc.

ASP.NETMVC2.jpg

Fig. 2 - HTML rendered using For Loop

If we use a foreach loop instead of a for loop then the collection won't post because if we use a foreach loop then the name field for each item in the rendered HTML will be as in the following Fig. 3.

ASP.NETMVC3.jpg

Fig. 3 HTML rendered using foreach loop.

Another important thing to note in "_AllTweets.cshtml" is that we have used @Html.HiddenFor() for the fields like id, Date and Text, that are displayed using @Html.DisplayFor() just above. Since DisplayFor() won't post a value to the controller we use @Html.HiddenFor(). By clicking the "Add" button in "_AllTweets.cshtml" the following action will be called. Since the entire collection is posted back in "viewModel.Tweets", we will add the new Tweet into that collection and return the view with updated Model.

  1. /// <summary>  
  2. /// Add posted tweet from TweetViewModel to tweet collection  
  3. /// </summary>  
  4. /// <param name="viewModel"></param>  
  5. /// <returns></returns>  
  6. [HttpPost]  
  7. public ActionResult AddTweet(TwitterViewModel viewModel)  
  8. {  
  9.     try  
  10.     {  
  11.         viewModel.Tweets.Add(viewModel.Tweet);  
  12.         return PartialView("_AllTweets", viewModel);  
  13.     }  
  14.     catch  
  15.     {  
  16.         return View();  
  17.     }  
  18. } 
}ASP.NETMVC4.jpg

Fig. 4
 
In Fig. 4 above we can see the SaveTweet() post action, where "TwitterViewModel" is posted back, that has the value for all Tweets collections.


Similar Articles