Saturday, March 15, 2014

Render ASP.NET MVC 4 Partial View based from Html.DropdownList() selected value using jQuery

In my previous post on loading items to Select control, I decided to create a more advanced example by rendering an asp.net mvc partial view using jquery based on drop down selection. The mvc application will simply load all orders irregardless of the status made by a particular customer selected from the dropdown list. The application also calculates the total orders made by the customer using jquery numberformatter framework.
Partial View:
 @model IList<ShowWebGridUsingJQuery.Models.SalesOrderHeader>  
 @{  
   Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";  
 }  
 @{  
   var orderTotal = Model.Sum(o => (float)o.TotalDue);  
   WebGrid grid = new WebGrid(Model);  
 }  
 <script type="text/javascript">  
   $(document).ready(function () {  
     var total = 0;  
     $('#divGrid .totalDue').each(function () {  
       total = total + parseFloat($(this)[0].innerHTML.toLocaleString().replace(",", ""));  
     });  
     $('table').append('<tfoot><tr><td colspan="7" style="text-align:right;"><b>Total</b></td><td style="text-align:center;"><b>' + NumberFormatter(total) + '</b></td></tr></tfoot>');  
   });  
   //using jquery plugin  
   function NumberFormatter(amount) {  
     var n = $.formatNumber(amount, { format: "#,###.00", locale: "us" });  
     return n;  
   }  
 </script>  
 <div id="divGrid">  
   @grid.GetHtml(  
     tableStyle: "webgrid", headerStyle: "webgrid-header", footerStyle: "webgrid-footer", alternatingRowStyle: "webgrid-alternating-row",  
     selectedRowStyle: "webgrid-selected-row", rowStyle: "webgrid-row-style",  
     columns:grid.Columns(  
       grid.Column("SalesOrderNumber", "Order ID"),  
       grid.Column("AccountNumber", "Account Number"),  
       grid.Column("OrderDate", "Order Date", format: (item) => string.Format("{0:yyyy-MM-dd}", item.OrderDate)),  
       grid.Column("CreditCardID","Credit Card ID"),  
       grid.Column("SubTotal","Sub Total", format: (item) => string.Format("{0:0,0.00}", item.SubTotal)),   
       grid.Column("TaxAmt","Tax Amount",format: (item) => string.Format("{0:0,0.00}", item.TaxAmt)),  
       grid.Column("Freight","Freight",format: (item) => string.Format("{0:0,0.00}", item.Freight)),  
       grid.Column("TotalDue","Total Due",format: (item) => string.Format("{0:0,0.00}", item.TotalDue), style: "totalDue"))  
      )  
 </div>  
Index View:
 <script type="text/javascript">  
   $(document).ready(function () {  
     $('#dvSalesOrdersLoader').hide();  
     $("#Customer").change(function () {  
       if ($("#Customer").val() != "Select") {  
         //show div with loading image (processing request)  
         $('#dvSalesOrdersLoader').show();  
         //working ajax  
         $.ajax({  
           url: '/Home/StateProvinces',  
           type: 'POST',  
           data: "CustomerID=" + $("#Customer").val(),            
           dataType: 'html'  
         })  
           .success(function (result) {  
             $('#dvSalesOrders').html("");  
             $('#dvSalesOrdersLoader').hide();  
             $('#dvSalesOrders').show();  
             $('#dvSalesOrders').html(result);  
           })  
           .error(function(xhr, status) {  
             alert(status);  
           });  
       }  
       else {  
         $('#dvSalesOrdersLoader').show();  
       }  
     });  
   });  
 </script>  
 @*@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "countryRegionsForm" }))*@  
 @using (Html.BeginForm())  
  {  
   @Html.AntiForgeryToken()  
   <h4>Select Customer Name:</h4>  
   <hr />  
    @Html.ValidationSummary()  
   <div>  
     @Html.Label("Select CustomerInfo:")  
     <div>  
       @Html.DropDownList("Customer", ViewData["CustomerInfo"] as SelectList)  
     </div>  
   </div><br />  
    <div>  
     @Html.Label("Order List")  
       <div id="dvSalesOrdersLoader" style="width: 100%; height: 130px">  
         <table style="width: 100%; height: 100%">  
           <tr>  
             <td>  
               <img src="~/Images/loader.gif" style="margin-top: 55px; margin-left: 200px" alt="not showing"/>  
             </td>  
           </tr>  
         </table>   
       </div>  
       <div id="dvSalesOrders" style="width: 100%; height: 100%; overflow:hidden; display:none">  
       </div>  
   </div>  
  }  
Controller:
Code:
private CustomerWithOrders context = new CustomerWithOrders();

        public ActionResult Index()
        {
            SelectList customers;

            // Join on the ID properties.
            var query = (from c in context.Customers
                        join p in context.People on c.CustomerID equals p.BusinessEntityID
                        select new 
                        { 
                            FullName =  p.FirstName + " " + (p.MiddleName != null ? p.MiddleName : "") + " " + p.LastName,
                            ID = c.CustomerID
                        }).ToList().OrderBy(t=>t.FullName);

            customers = new SelectList(query.ToList(), "ID", "FullName");
            ViewData["CustomerInfo"] = customers;

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult StateProvinces(string CustomerID)
        {
            int temp = Convert.ToInt32(CustomerID);
            List<SalesOrderHeader> orderDetails = new List<SalesOrderHeader>();

            (from sales in context.Sales_Order_Header
             where sales.CustomerID == temp   
             select sales).ToList().ForEach(item =>
                     {
                         orderDetails.Add(item);
                     });
                        
            return View("~/Views/Shared/_SalesOrders.cshtml", orderDetails);
        }
Customer with sales orders:

Customer without sales orders:
Cheers!

0 comments:

Post a Comment