创建Ajax搜索页面--返回Json数据(6)

1.Controllers中添加如下代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Test.Models;

namespace Test.Controllers
{
    public class AppointmentController : Controller
    {
        //
        // GET: /Appointment
        public ActionResult Index(string id)
        {
            return View("Index", (object)id);
        }
 
        public ViewResult AppointmentData(string id)
        {
            IEnumerable<Appointment> data = new[] {
                 new Appointment { ClientName = "张三", Date = DateTime.Parse("1/1/2012")}, 
                 new Appointment { ClientName = "李四", Date = DateTime.Parse("2/1/2012")}, 
                 new Appointment { ClientName = "王五", Date = DateTime.Parse("3/1/2012")}, 
                 new Appointment { ClientName = "赵六", Date = DateTime.Parse("1/20/2012")}, 
                 new Appointment { ClientName = "田七", Date = DateTime.Parse("1/22/2012")}, 
                 new Appointment {ClientName = "黄九", Date = DateTime.Parse("2/25/2012")}, 
                 new Appointment {ClientName = "路人甲", Date = DateTime.Parse("2/25/2013")}
            };
            if (!string.IsNullOrEmpty(id) && id != "All")
            {
                data = data.Where(e => e.ClientName == id);
            }
            return  View(data);
        }
        public JsonResult JsonData(string id)
        {
            IEnumerable<Appointment> data = new[] {
                 new Appointment { ClientName = "张三", Date = DateTime.Parse("1/1/2012")}, 
                 new Appointment { ClientName = "李四", Date = DateTime.Parse("2/1/2012")}, 
                 new Appointment { ClientName = "王五", Date = DateTime.Parse("3/1/2012")}, 
                 new Appointment { ClientName = "赵六", Date = DateTime.Parse("1/20/2012")}, 
                 new Appointment { ClientName = "田七", Date = DateTime.Parse("1/22/2012")}, 
                 new Appointment {ClientName = "黄九", Date = DateTime.Parse("2/25/2012")}, 
                 new Appointment {ClientName = "路人甲", Date = DateTime.Parse("2/25/2013")}
            };
            if (!string.IsNullOrEmpty(id) && id != "All")
            {
                data = data.Where(e => e.ClientName == id);
            }
            //客户端不需要用TermsAccepted属性,所以也就不需要把它发送到客户端
            //将Date转为String操作在服务端更加容易
            var formattedData = data.Select(m => new
            {
                ClientName = m.ClientName,
                Date = m.Date.ToShortDateString(),
                TermsAccepted = m.TermsAccepted
            });
            //默认情况下,JSON数据仅仅在响应POST请求时发送,传递这个枚举值就告诉MVC框架响应Get请求并传递Json数据。
            //第三方的站点是可以截取响应Get请求时返回的JSON数据,所以默认情况下只响应Post请求的JSON数据
            return Json(formattedData, JsonRequestBehavior.AllowGet);
        }


    }
}

2.Index修改为如下

@model string
@{
    ViewBag.Title = "Appointment";
    AjaxOptions ajaxOpts = new AjaxOptions
    {
        UpdateTargetId = "tabledata",
        Url = Url.Action("AppointmentData"),
        LoadingElementId = "loading",
        LoadingElementDuration = 2000,
        Confirm = "提交请求?"
    };
}
<h2>
    Appointment List</h2>
<div id="loading" style="display: none; color: Red; font-weight: bold">
    <p>
        Loading Data</p>
</div>
@using (Ajax.BeginForm(ajaxOpts))
{
    <table>
        <thead>
            <th>
                Client Name
            </th>
            <th>
                Appointment Date
            </th>
        </thead>
        <tbody id="tabledata">
            @Html.Action("AppointmentData", new { id = Model })
        </tbody>
    </table>
}
@foreach (string str in new[] { "All", "张三", "李四", "王五" })
{
    <div style="margin-right: 5px; float: left">
        @Ajax.ActionLink(str, "Index", new { id = str },
            new AjaxOptions
            {
                LoadingElementId = "loading",
                Url = Url.Action("JsonData", new { id = str }),
                OnSuccess = "OnSuccess"
            })
    </div>
}
 

3._Layout.cshtml修改为如下

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="http://www.cnblogs.com/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        function OnSuccess(data) {
            var target = $("#tabledata");
            target.empty();
            for (var i = 0; i < data.length; i++) {
                target.append('<tr><td>' + data[i].ClientName + '</td><td>'
                + data[i].Date + '</td></tr>');
            }
            alert(JSON.stringify(data));
        }
 
    </script>
</head>
<body>
    @RenderBody()
</body>
</html>

 效果图:

  

 4.合并上述代码

  1.AppointmentController修改为:

 public class AppointmentController : Controller
    {
        //
        // GET: /Appointment
        public ActionResult Index(string id)
        {
            return View("Index", (object)id);
        }
 
        public ActionResult AppointmentData(string id)
        {
            IEnumerable<Appointment> data = new[] {
                 new Appointment { ClientName = "张三", Date = DateTime.Parse("1/1/2012")}, 
                 new Appointment { ClientName = "李四", Date = DateTime.Parse("2/1/2012")}, 
                 new Appointment { ClientName = "王五", Date = DateTime.Parse("3/1/2012")}, 
                 new Appointment { ClientName = "赵六", Date = DateTime.Parse("1/20/2012")}, 
                 new Appointment { ClientName = "田七", Date = DateTime.Parse("1/22/2012")}, 
                 new Appointment {ClientName = "黄九", Date = DateTime.Parse("2/25/2012")}, 
                 new Appointment {ClientName = "路人甲", Date = DateTime.Parse("2/25/2013")}
            };
            if (!string.IsNullOrEmpty(id) && id != "All")
            {
                data = data.Where(e => e.ClientName == id);
            }

            if (Request.IsAjaxRequest())
            {
                return Json(data.Select(m => new
                {
                    ClientName = m.ClientName,
                    Date = m.Date.ToShortDateString()
                }), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return View(data);
            }
        }
     


    }

 2.Index修改为

@foreach (string str in new[] { "All", "张三", "李四", "王五" })
{
    <div style="margin-right: 5px; float: left">
        @Ajax.ActionLink(str, "Index", new { id = str },
            new AjaxOptions
            {
                LoadingElementId = "loading",
                Url = Url.Action("AppointmentData", new { id = str }),
                OnSuccess = "OnSuccess"
            })
    </div>
}

日期的格式化操作

  1.在Web.Config中修改环境变量

       <globalization uiCulture="en" culture="en-US" />

  2.js格式化日期

        function formatDate(jsonDate) {
            var date = new Date(parseInt(jsonDate.substr(6)))
            return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
        }

  

  

 

posted @ 2012-11-08 11:21  bradleydan  阅读(293)  评论(0)    收藏  举报