本文转自:http://www.binaryintellect.net/articles/218ca630-ba50-48fe-af6e-6f754b5894aa.aspx

Most of the times ASP.NET MVC views are rendered as a result of user  navigating to some action. For example, when 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 is rendered as a result of a full GET or POST request. At times,  however, you may want to load views dynamically through Ajax. This way you 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 Northwind database. Each customer row has two 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  have submitted the page back to the server and then returned a view with the  corresponding details. Using Ajax you can display the details without causing  any postback to the server. This is shown below:

As you 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 you have two 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 be said  that the former approach is suitable to make calls to Web API or when HTML  display is dynamically decided by the client script. The later approach is  suitable when ASP.NET MVC strongly typed views (or partial views) are being used  to render the UI. In this example we will be using the later approach.

To develop this example, create a new ASP.NET MVC application based on the  Empty template. Then add ADO.NET 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)
.OrderBy(o => o.OrderID).ToList();
}
}
return PartialView(viewName,model);
}

The GetView() action method accepts two parameters - customerID and viewName.  These two parameters are passed through an Ajax request. Depending on the  viewName parameter either CustomerDetails partial view is returned to the caller  or OrderDetails partial view is returned. These two view 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 is passed to the PartialView() method. Here, we used  partial views because the HTML output is to be inserted in an existing page  through Ajax.

Next, add one view (Index.cshtml) and two 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="10">
<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 table.

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

@model List<MVCViewsThroughAjax.Models.Order>

<table border="1" cellpadding="10">
<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>

...
<html>
<head>
...
</head>
<body>
<div id="viewPlaceHolder"></div>
<br /><br />
<table border="1" cellpadding="10">
<tr>
<th>Customer ID</th>
<th>Company Name</th>
<th colspan="2">Actions</th>
</tr>
@foreach(var item in Model)
{
<tr>
<td>@item.CustomerID</td>
<td>@item.CompanyName</td>
<td><input type="button" class="customerDetails"
value="Customer Details" /></td>
<td><input type="button" class="orderDetails"
value="Order Details" /></td>
</tr>
}
</table>
</body>
</html>

The Index view receives a List of Customer entities as its model and renders  a table with CustomerID, CompanyName and two 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 of the body section? The  viewPlaceHolder is where the output of CustomerDetails.cshtml and  OrderDetails.cshtml will be loaded. To do so we will use load() method of jQuery.  Here is how that can be 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" });
});
});

Recollect that Customer Details and Order Details buttons have assigned CSS  class of customerDetails and orderDetails respectively. The above jQuery code  uses class selector to wire click event handlers to the respective buttons.  Inside the click event handler of Customer Details button, the code retrieves  the CustomerID from the table row. This is done using closest(), children() and  first() methods. The CustomerID is stored in custID variable. Then load() method  is called on viewPlaceHolder <div>. The first parameter of the load() method is  the URL that will be 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 two parameters - customerID and viewName.  Hence the object has customerID and viewName properties. The customerID property  is set to custID variable and viewName is 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 Ajax requests are 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 are empty or contain invalid values you can throw an exception.

[转]Load ASP.NET MVC Partial Views Dynamically Using jQuery的更多相关文章

  1. 【番外篇】ASP.NET MVC快速入门之免费jQuery控件库(MVC5+EF6)

    目录 [第一篇]ASP.NET MVC快速入门之数据库操作(MVC5+EF6) [第二篇]ASP.NET MVC快速入门之数据注解(MVC5+EF6) [第三篇]ASP.NET MVC快速入门之安全策 ...

  2. ASP.NET MVC的客户端验证:jQuery的验证

    之前我们一直讨论的Model验证仅限于服务端验证,即在Web服务器根据相应的规则对请求数据实施验证.如果我们能够在客户端(浏览器)对用户输入的数据先进行验证,这样会减少针对服务器请求的频率,从而缓解W ...

  3. 使用RazorEngine对ASP.NET MVC的Views进行UnitTest

    有的时候我们需要对Razor最后生产的文本(HTML OR XML OR..)进行单元测试. 使用Nuget安装RazorEngine. 新建一个ASP.NET MVC项目,并且带有测试项目. 修改I ...

  4. asp.net mvc Partial OutputCache 在SpaceBuilder中的应用实践

    最近给SpaceBuilder增加OutputCache 时发现了一些问题,贴在这做个备忘,也方便遇到类似问题的朋友查阅. 目前SpaceBuilder表现层使用是asp.net mvc v1.0,使 ...

  5. ASP.NET MVC 4 (十一) Bundles和显示模式--asp.net mvc中 @Scripts.Render("~/bundles/jquery")是什么意思? 在布局文件中使用Scripts.Render()输出脚本包,Styles.Render()输出风格包:

    ASP.NET MVC 4 (十一) Bundles和显示模式 ASP.NET MVC 4 引入的js打包压缩功能.打包压缩jquery目录下的文件,在布局文件中使用Scripts.Render()输 ...

  6. ASP.NET MVC的客户端验证:jQuery验证在Model验证中的实现

    在简单了解了Unobtrusive JavaScript形式的验证在jQuery中的编程方式之后,我们来介绍ASP.NET MVC是如何利用它实现客户端验证的.服务端验证最终实现在相应的ModelVa ...

  7. ASP.NET MVC Partial页输出JS

    很多情况Partial是需要引用到JS的,通常做法是吧JS在引用Partial的页面中加入JS文件或者JS代码. 前阵子网上看到一段代码可以在Partial页面中添加JS,输出道引用页面. publi ...

  8. [ASP.NET MVC]@Partial 和@RenderPartial的区别

    @Partial 和@RenderPartial的区别 Html.partial和RenderPartial的用法与区别 Html.partial和RenderPartial都是输出html片段,区别 ...

  9. ASP.NET MVC中,怎么使用jquery/ajaxForm上传文件

    ajaxForm插件最好选择:jquery forms plugin. 以下为示例: Ajax.BeginForm @using (Ajax.BeginForm("YourAction&qu ...

随机推荐

  1. 八、Node.js-http模块

    JS代码如下: /* 如果我们使用PHP来编写后端的代码时,需要Apache 或者 Nginx 的HTTP 服务器,并配上 mod_php5 模块和php-cgi,来处理客户端的请求相应. 不过对 N ...

  2. 返回类型和 return 语句

    return 语句终止当前正在执行的函数并将控制权返回到调用该函数的地方.return 语句有两种形式: return; return expression; 不要返回局部对象的引用或指针: 函数完成 ...

  3. hadoop集群配置方法---mapreduce应用:xml解析+wordcount详解---yarn配置项解析

    注:以下链接均为近期hadoop集群搭建及mapreduce应用开发查找到的资料.使用hadoop2.6.0,其中hadoop集群配置过程下面的文章都有部分参考. hadoop集群配置方法: ---- ...

  4. 微信支付的SDK曝出重大漏洞(XXE漏洞)

    一.背景 昨天(2018-07-04)微信支付的SDK曝出重大漏洞(XXE漏洞),通过该漏洞,攻击者可以获取服务器中目录结构.文件内容,如代码.各种私钥等.获取这些信息以后,攻击者便可以为所欲为,其中 ...

  5. [JSOI2007]麻将 模拟 BZOJ1028

    题目描述 麻将是中国传统的娱乐工具之一.麻将牌的牌可以分为字牌(共有东.南.西.北.中.发.白七种)和序数牌(分为条子.饼子.万子三种花色,每种花色各有一到九的九种牌),每种牌各四张. 在麻将中,通常 ...

  6. 【第一周】 网络爬虫之规则 北京理工大学嵩天 mooc

    rrequests库的7个主要方法 方法 说明 requests.request() 构造一个请求,支撑以下各方法的基础方法 requests.get() 获取HTML网页的主要方法,对应于HTTP的 ...

  7. python之读取文件的测试数据

    假设我们有一个叫testdata.txt的文件,现在在这个文件里面有测试数据,我们怎么利用前2小章学习的知识,读取测试数据呢? 测试数据如下: url:https://www.cnblogs.com/ ...

  8. 洛谷 P3616 富金森林公园题解(树状数组)

    P3616 富金森林公园 题目描述 博艾的富金森林公园里有一个长长的富金山脉,山脉是由一块块巨石并列构成的,编号从1到N.每一个巨石有一个海拔高度.而这个山脉又在一个盆地中,盆地里可能会积水,积水也有 ...

  9. 在URL地址栏中显示ico

             <!-- 在URL地址栏中显示ico -->         <link Rel="SHORTCUT ICON" href="imag ...

  10. os.path模块

    什么是os.path模块 该模块用于处理路径,我们知道python是一门跨平台的语言,二每种操作系统,文件路径是截然不同的,为了使程序可以在不同平台生正确运行,python提供了该模块,使用该模块可以 ...