使用jquery加载部分视图02-使用$.ajax()

本篇体验使用$.ajax()加载部分视图。与加载部分视图相关的包括:

RenderPartial和RenderAction区别  
使用jquery加载部分视图01-使用$.get()      

□ HomeController

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
 
        public ActionResult GetTeams()
        {
            List<Team> teams = new List<Team>
            {
                new Team(){ID = 1,Name = "广州恒大",Rank = 1},
                new Team(){ID = 2, Name = "山东鲁能", Rank = 2},
                new Team(){ID=3, Name = "北京国安", Rank = 3}
            };
            return PartialView("_ShowTeams", teams);
        }
    }

□ View Model

    public class Team
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Rank { get; set; }
    }

□ 部分视图_ShowTeams.cshtml

@model IEnumerable<_02.Models.Team>
 
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Rank)
        </th>
    </tr>
 
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Rank)
        </td>
    </tr>
}
</table>
 

□ 主视图Index.cshtml
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 
<h2>Index</h2>
<div id="tm"></div>
 
@section scripts
{
    <script type="text/javascript">
        $(function() {
            $.ajax({
                url: '@Url.Action("GetTeams","Home")',
                contentType: 'application/html;charset=utf-8',
                type: 'GET',
                dataType: 'html',
                success: function(result) {
                    $('#tm').html(result);
                },
                error: function(xhr, status) {
                    alert(status);
                }
            });
        });
    </script>
}
 

效果:       

1

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值