Go Load ASP. NET MVC Partial views dynamically Using JQuery

Source: Internet
Author: User

This article transferred from: http://www.binaryintellect.net/articles/218ca630-ba50-48fe-af6e-6f754b5894aa.aspx

Most of the Times ASP. NET MVC views is rendered as a result of the user navigating to some action. For example, if a user navigates to/home/index in the browser (either through address bar or through a hyperlink), ASP . NET MVC executes the action method and usually returns a view to the browser. This means each view was rendered as a result of a full GET or POST request. At times, however and want to load views dynamically through Ajax. This is the can render contents of a view without full page refresh.

Consider the following page:

The above page consists of a table that lists customers from the Customers table of the Northwind database. Each customer row has a Buttons-customer details and Order details. Clicking on the respective button should display customer details and order details from the database. Without Ajax you would has submitted the page back to the server and then returned a view with the corresponding detail S. Using Ajax can display the details without causing any postback to the server. This is shown below:

As can see the above figure shows order details for CustomerID ALFKI above the Customers table. These details are fetched via Ajax request.

While displaying data through Ajax request has both options:

    • Fetch raw data from the server and embed it in HTML markup on the client side
    • Fetch HTML markup with data embedded from the server

Although the choice of the approach depends on a situation, it can being said that the former approach are suitable to make C Alls to Web API or when HTML display is dynamically decided by the client script. The later approach is suitable when the ASP. NET MVC strongly typed views (or partial views) were being used to render the UI. In this example we'll be using the later approach.

To develop this example, create a new ASP. NET MVC application based on the Empty template. Then add ADO Entity Data Model for Customers and Orders tables of Northwind database. The Customer and Order entities are shown below:

Next, add HomeController and write the Index () action method as shown below:

Public ActionResult Index () {    using (northwindentities db = new NorthwindEntities ())    {        List<customer > model = db. Customers.tolist ();        return View (model);}    }

The index () action simply retrieves all the Customer entities from the Customers DbSet and passes them to the index view.

Now, add another action Method-getview () – to the HomeController as shown below:

Public ActionResult GetView (string customerid,string viewName) {    object model = NULL;    if (viewname== "CustomerDetails")    {        using (northwindentities db=new northwindentities ())        {            model = db . Customers.find (CustomerID);        }    }    if (ViewName = = "OrderDetails")    {        using (northwindentities db = new NorthwindEntities ())        {            model = db . Orders.where (o = O.customerid = = CustomerID)                      . (o = O.orderid). ToList ();        }    }    Return Partialview (Viewname,model);}

The GetView () Action method accepts the Parameters-customerid and ViewName. These parameters is passed through an AJAX request. Depending on the viewName parameter either customerdetails partial view are returned to the caller or OrderDetails Partia L view is returned. These the need model in the form of a Customer object and a List of Order entities respectively. That's why model variable is declared as object. Once model variable is populated the partial view name and the model are passed to the Partialview () method. Here, we used partial views because the HTML output are to be inserted on an existing page through Ajax.

Next, add one view (index.cshtml) and both partial views (customerdetails.cshtml and orderdetails.cshtml) to the Home sub- folder of views folder.

ADD the following markup to the customerdetails.cshtml partial view:

@model mvcviewsthroughajax.models.customer<table border= "1" cellpadding= "ten" >    <tr>        <td> Customer ID:</td>        <td> @Model .customerid</td>    </tr>    <tr>        <td >company Name:</td>        <td> @Model .companyname</td>    </tr>    <tr>        <td>contact Name:</td>        <td> @Model .contactname</td>    </tr>    <tr >        <td>country:</td>        <td> @Model .country</td>    </tr></table >

The above markup is quite straightforward. The customerdetails partial view simply displays CustomerID, CompanyName, ContactName and country of a Customer in a tab Le.

Now add the following markup to the orderdetails.cshtml partial page:

@model list<mvcviewsthroughajax.models.order><table border= "1" cellpadding= "ten" >    <tr>        <th>order id</th>        <th>order date</th>        <th>shipping Date</th>        < th>shipped to</th>    </tr>    @foreach (var item in Model)    {         <tr>            <td>@ Item. Orderid</td>            <td> @item. Orderdate</td>            <td> @item. Shippeddate</td>            <td> @item. shipcountry</td>        </tr>    }</table>

The above markup iterates through the List of Order entities and renders a table with four Columns-orderid, OrderDate, ShippedDate and ShipCountry.

Now, add the following markup to the Index view:

 @model List<mvcviewsthroughajax.models.customer>...

The Index view receives a List of Customer entities as its model and renders a table with CustomerID, CompanyName and Buttons-customer details and Order details.

Now comes the important part-making Ajax calls to display customer details and order details. Noticed the <div> at the beginning? The Viewplaceholder is where the output of customerdetails.cshtml and orderdetails.cshtml would be loaded.  To doing so we'll use load () method of JQuery. Here's how the can be was done:

 $ (document). Ready (function () {$ (". CustomerDetails"). Click (function (evt) {var cell=$ (evt.target). Closest        ("tr"). Children (). First (); var custid=cell.text ();  $ ("#viewPlaceHolder"). Load ("/home/getview", {customerid:custid, viewName: "CustomerDetails"    });    });        $ (". OrderDetails"). Click (function (evt) {var cell = $ (evt.target). Closest ("tr"). Children (). First (); var CustID = Cell.text ();  $ ("#viewPlaceHolder"). Load ("/home/getview", {customerid:custid, viewName: "OrderDetails"}); /strong>}); 

Recollect that Customer details and Order details buttons has assigned css  class of CustomerDetails and OrderDetail s respectively. The above JQuery code  uses class selector to wire click event handlers to the respective buttons.  Inside the C Lick event handler of the Customer Details button, the code retrieves  the CustomerID from the table row. This was done using closest (), children () and  first () methods. The CustomerID is stored in CustID variable. Then load () method  are called on Viewplaceholder <div>. The first parameter of the load () method is  the URL that would be a requested through an AJAX request. The second parameter is  a JavaScript object that supplies the data needed by the requested URL. In our  example, GetView () action method needs. Parameters-customerid and viewname.  Hence the object has C Ustomerid and ViewName properties. The CustomerID property  is set to CustID variable and viewName are set to CustomerdEtails.

The Click event handler of Order Details is similar but loads OrderDetails partial view.

That ' s it! You can now run the application and try clicking on both the buttons. The following figure shows customer details loaded successfully.

Notice that through out the application run the URL shown in the browser address bar remains unchanged indicating that Aj Ax requests is being made to display customer details and order details.

In the above example Ajax requests were made To/home/getview action. A user can also enter this URL in the browser ' s address bar producing undesirable results. As a precaution you can check the CustomerID and ViewName parameters inside the GetView () action method (not shown in the Above code). If These parameters is empty or contain invalid values you can throw a exception.

[]load ASP. NET MVC Partial views dynamically Using JQuery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.