ASP.NET (C#) Question

How To Pass Model Object To View in Asp.Net MVC Using Ajax


@model IEnumerable<InfinityWeb.Models.Orders>
foreach(var item in Model)
<label> item.OrderId </label> <br/> @* it display all students name *@

@* Below is just DropDown for making request to controller *@

<div class="dropdown ">
<button class="btn dropdown-toggle"type="button" id="menu1" data-toggle="dropdown">
Select Orders
<span class="caret"></span>
<ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
<li role="presentation"><a role="menuitem" href="@Url.Action("MonthOrders", "Admin")">This month orders</a></li>
<li role="presentation"><a role="menuitem" href="@Url.Action("TodayOrders", "Admin")">Today Orders</a></li>

Controller - returns new model to same View to iterate over monthly orders

public ActionResult MonthOrders()
return View("Index", orders.GetMonthOrders());

The above code works fine, but instead of making call to load whole page I want to make a Ajax request while changing dropdown and receive a Orders Model From a JsonResult action method, so that I can use that model in my
loop to iterate over
such as below

public JsonResult MonthlyOrders()
// ??

And also how would View's Model will receive that object


You can create a partial view which is strongly typed to a collection of your Orders class. Put the code for looping through the items and displaying in that. Then include this partial view in your main view.

Now for your ajax method, change the return type to ActionResult and return the partial view result. You can build the collection of Orders and pass that list to the same partial view. So your ajax call's response will be the html rendered by the partial view.

Create a partial view called OrderTable.cshtml and have this code

@model IEnumerable<InfinityWeb.Models.Orders> 
foreach(var item in Model)
  <label> item.OrderId </label> <br/>  

Now in your MonthlyOrders, return this view with data

public ActionResult MonthlyOrders()
    var orderList = new List<Orders>();
    // to do : Load data to orderList variable.
    return View("OrderTable.cshtml",orderList)

Now in your main view you will include this partial view inside a container div

@model IEnumerable<InfinityWeb.Models.Orders> 
<div id="orders">

Now when your ajax calls gets data from server, simply replace the content of the div with id "orders"