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中输入如下代码:


<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中输入


<% /* %><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请求,前端视图为:



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

    
<%=Html.TextBox("search"%>
    
<input type="button" value="查询" id="btnSearch" />
    <div id="results">
        
<%Html.RenderPartial("NewsListPartial", Model); %>
    
</div>

    
<script language="javascript" type="text/javascript">
        $(
"#btnSearch").click(function() {
        $.get($(
this).attr("href"), { title: $("#search").attr("value") }, function(response) {
                $(
"#results").html(response);
            })

        });
    
</script>

NewsListPartial.ascx中的内容为:


<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<News>>" %>

    
<table>
        
<tr>
           
            
<th>
                Author
            
</th>
            
<th>
                Title
            
</th>
            
<th>
                CreateTime
            
</th>
        
</tr>

    
<% foreach (var item in Model) { %>
    
        
<tr>
       
            
<td>
                
<%= Html.Encode(item.Author) %>
            
</td>
            
<td>
                
<%= Html.Encode(item.Title) %>
            
</td>
            
<td>
                
<%= Html.Encode(String.Format("{0:g}", item.CreateTime)) %>
            
</td>
        
</tr>
    
    
<% } %>

    
</table>

Controller为:


public ActionResult GetDemo(string title)
        {
            List
<News> news=ListNews.GetList();
            
if (Request.IsAjaxRequest())
            {
                
return View("NewsListPartial",news.Where(p => 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) {
                $("#results").html(response);
            }:当ajax请求完之后会调用这个函数,这个函数会将id=results的div替换成返回的文本内容。

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

略(见源码)

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


    <%=Html.TextBox("NewsId"%>
    
<input type="button" id="btnGet" value="获得新闻" />
    
<table>
        
<tr>
            
<td>
                ID:
            
</td>
            
<td id="ID">
            
</td>
        
</tr>
        
<tr>
            
<td>
                作者:
            
</td>
            
<td id="Author">
            
</td>
        
</tr>
        
<tr>
            
<td>
                标题:
            
</td>
            
<td id="Title">
            
</td>
        
</tr>
   
    
</table>

    
<script language="javascript" type="text/javascript">
        $(
"#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);
            })
        })
    
</script>

Controller:


public ActionResult JosnDemo(string newsID)
        {
            
if (Request.IsAjaxRequest())
            {
                
return new JsonResult
                {
                    Data 
= ListNews.GetList().First(p => p.ID.ToString() == newsID)
                };
            }
            
else
                
return View();
        }

 

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

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

View:


<h2>
        NewsList
</h2>
    
<%=Html.DropDownList("Author"%>
    
<div id="results">
        
<%Html.RenderPartial("NewsListPartial", Model); %>
    
</div>
    
<script language="javascript" type="text/javascript">

        $(
"#Author").change(function() {
            var selection 
= $("#Author").val();
            $(
"#results").load($(this).attr("href"), { author: selection });
        })
    
</script>

 

Controller:


public ActionResult NewsList(string author)
        {
            
            List
<News> news=ListNews.GetList();
            
if (Request.IsAjaxRequest())
            {
                
if (!string.IsNullOrEmpty(author))
                {
                    news 
= news.Where(p => p.Author == author).ToList();
                }
                
return View("NewsListPartial", news);
            }
            
else
            {
                List
<object> list = new List<object>();
                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》

四、源码下载

posted @ 2009-11-04 18:11  你听海是不是在笑  阅读(5036)  评论(0编辑  收藏  举报