天天看点

ASP.NET MVC实践系列5-结合jQuery

现在做web开发肯定都听说过jQuery,jQuery在ASP.NET MVC被支持的很好,而且据说vs2010中也会集成进去,所以使用ASP.NET MVC了解jQuery肯定有莫大的好处,所以这里利用几个简单的例子来讲解一下jQuery在ASP.NET MVC的中应用。

一、jQuery的引用

对于一个新的ASP.NET MVC项目来说在它的scripts文件夹下已经包含了jQuery的js文件,所以我们在项目中直接引用就可以了,我们可以在View中输入如下代码:

ASP.NET MVC实践系列5-结合jQuery

<head runat="server">

<script src="<%= Url.Content("~/Scripts/jquery-1.3.2.min.js") %>"

type="text/javascript"></script>

</head>

这里的min版本去除了空格,注释,改写了长文件名,下载的时候所用过的时间更少。

在Vs中使用jQuery有一个比较大的好处是可以利用智能感知,jQuery的团队和微软的团队共同开发了一个js文件用于在vs中的jQuery可以智能感知,但需要在View中输入

ASP.NET MVC实践系列5-结合jQuery

<% /* %><script src="~/Scripts/jquery-1.3.2-vsdoc.js"></script><% */ %>

不过我测试这个的时候发现如果在具体的View中使用了这个引用会影响在View中代码的智能感知,但如果放在mastpage中就没什么问题了。

二、jQuery中使用Ajax方式:

1、jQuery.get(url, [data], [callback], [type])

urlString:待载入页面的URL地址

data (可选)Map:待发送 Key/value 参数,在服务器端可以用Request获得。

callback (可选)Function:载入成功时回调函数。

type (可选)String:返回内容格式,xml, html, script, json, text, _default。

我们现在要做一个对列表进行查询的ajax请求,前端视图为:

<a></a>

ASP.NET MVC实践系列5-结合jQuery

    &lt;script src="&lt;%= Url.Content("~/Scripts/jquery-1.3.2.min.js") %&gt;" type="text/javascript"&gt;&lt;/script&gt;

    &lt;%=Html.TextBox("search") %&gt;

    &lt;input type="button" value="查询" id="btnSearch" /&gt;

    &lt;div id="results"&gt;

        &lt;%Html.RenderPartial("NewsListPartial", Model); %&gt;

    &lt;/div&gt;

    &lt;script language="javascript" type="text/javascript"&gt;

        $("#btnSearch").click(function() {

        $.get($(this).attr("href"), { title: $("#search").attr("value") }, function(response) {

                $("#results").html(response);

            })

        });

    &lt;/script&gt;

NewsListPartial.ascx中的内容为:

ASP.NET MVC实践系列5-结合jQuery

&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl&lt;IEnumerable&lt;News&gt;&gt;" %&gt;

    &lt;table&gt;

        &lt;tr&gt;

            &lt;th&gt;

                Author

            &lt;/th&gt;

                Title

                CreateTime

        &lt;/tr&gt;

    &lt;% foreach (var item in Model) { %&gt;

            &lt;td&gt;

                &lt;%= Html.Encode(item.Author) %&gt;

            &lt;/td&gt;

                &lt;%= Html.Encode(item.Title) %&gt;

                &lt;%= Html.Encode(String.Format("{0:g}", item.CreateTime)) %&gt;

    &lt;% } %&gt;

    &lt;/table&gt;

Controller为:

ASP.NET MVC实践系列5-结合jQuery

public ActionResult GetDemo(string title)

        {

            List&lt;News&gt; news=ListNews.GetList();

            if (Request.IsAjaxRequest())

            {

                return View("NewsListPartial",news.Where(p =&gt; p.Title.Contains(title)));

            }

            return View(news);

        }

我们重点来解释一下这句:

$.get($(this).attr("href"), { title: $("#search").attr("value") }, function(response) {

                $("#results").html(response);

            })

$(this).attr("href"):获得当前链接

{ title: $("#search").attr("value") }:调用url时传递的参数,这个参数就是TextBox的值。

function(response) {

            }:当ajax请求完之后会调用这个函数,这个函数会将id=results的div替换成返回的文本内容。

2、jQuery.post(url, [data], [callback], [type]) 的用法和get的用法很相似

略(见源码)

3、jQuery.getJSON(url, [data], [callback]) :通过 HTTP GET 请求载入 JSON 数据。

View:

ASP.NET MVC实践系列5-结合jQuery

    &lt;%=Html.TextBox("NewsId") %&gt;

    &lt;input type="button" id="btnGet" value="获得新闻" /&gt;

                ID:

            &lt;td id="ID"&gt;

                作者:

            &lt;td id="Author"&gt;

                标题:

            &lt;td id="Title"&gt;

        $("#btnGet").click(function() {

        $.getJSON($(this).attr("action"), { newsID: $("#NewsId").attr("value") }, function(news) {

                $("#ID").html(news.ID);

                $("#Author").html(news.Author);

                $("#Title").html(news.Title);

        })

Controller:

ASP.NET MVC实践系列5-结合jQuery

public ActionResult JosnDemo(string newsID)

                return new JsonResult

                {

                    Data = ListNews.GetList().First(p =&gt; p.ID.ToString() == newsID)

                };

            else

                return View();

4、load(url, [data], [callback]) :载入远程 HTML 文件代码并插入至 DOM 中。

下例中当DropDownList改变时,根据DropDownList中的内容改变列表

ASP.NET MVC实践系列5-结合jQuery

&lt;h2&gt;

        NewsList&lt;/h2&gt;

    &lt;%=Html.DropDownList("Author") %&gt;

        $("#Author").change(function() {

            var selection = $("#Author").val();

            $("#results").load($(this).attr("href"), { author: selection });

ASP.NET MVC实践系列5-结合jQuery

public ActionResult NewsList(string author)

                if (!string.IsNullOrEmpty(author))

                    news = news.Where(p =&gt; p.Author == author).ToList();

                }

                return View("NewsListPartial", news);

                List&lt;object&gt; list = new List&lt;object&gt;();

                list.Add(new { author = "全部", value = "" });

                list.Add(new { author = "lfm1", value = "lfm1" });

                list.Add(new { author = "lfm2", value = "lfm2" });

                list.Add(new { author = "lfm3", value = "lfm3" });

                ViewData["Author"] = new SelectList(list, "value", "author");

                return View(news);

三、参考:

《pro_asp_dot_net_mvc_framework》

《Professional ASP.NET MVC 1.0》

本文转自 你听海是不是在笑 博客园博客,原文链接:http://www.cnblogs.com/nuaalfm/archive/2009/11/04/1595411.html  ,如需转载请自行联系原作者

继续阅读