[JQuery]JQuery选择器

mikel阅读(800)

基本选择器

#myid 返回: <JQuery对象>
匹配一个id为myid的元素。
element 返回: <JQuery对象> 数组
匹配所有的element元素
.myclass 返回: <jQuery对象> 数组
匹配所有class为myclass的元素
* 返回: <jQuery对象> 数组
匹配所有元素。该选择器会选择文档中所有的元素,包括html,head,body
selector1,selector2,selectorN 返回: <jQuery对象> 数组
匹配所有满足selector1或selector2或selectorN的元素

层次选择

elementParent elementChild 返回: <jQuery对象> 数组
匹配elementParent下的所有子元素elementChild。例如:$("div p") 选择所有div下的p元素
elementParent > elementChild 返回: <jQuery对象> 数组
匹配elementParent下的子元素elementChild。例如:$("div>p") 选择所有上级元素为div的p元素
prev+next 返回: <jQuery对象> 数组
匹配prev同级之后紧邻的元素next。例如:$("h1+div") 选择所有div同级之前为h1的元素(<h1 /><div />)
prev ~ siblings 返回: <jQuery对象> 数组
匹配prev同级之后的元素siblings。例如:$("h1~div") 可以匹配(<h1 /><div /><div />)

基本滤镜

:first 返回: <jQuery对象>
匹配第一个元素
:last 返回: <jQuery对象>
匹配最后一个元素
:not(selector) 返回: <jQuery对象> 数组
匹配不满足selector的元素
:has(selector) 返回: <jQuery对象> 数组
匹配包含满足selector的元素。此选择器为1.2新增
:even 返回: <jQuery对象> 数组
从匹配的元素集中取序数为偶数的元素。
:odd 返回: <jQuery对象> 数组
从匹配的元素集中取序数为奇数的元素。
:eq(index) 返回: <jQuery对象> 数组
从匹配的元素集中取第index个元素
:gt(index) 返回: <jQuery对象> 数组
从匹配的元素中取序数大于index的元素
:lt(index) 返回: <jQuery对象> 数组
从匹配的元素中取序数小于index的元素
:header 返回: <jQuery对象> 数组
匹配所有的标题元素,例如h1,h2,h3……hN。此选择器为1.2新增
:animated 返回: <jQuery对象> 数组
匹配正在执行动画的元素。此选择器为1.2新增
:empty 返回: <jQuery对象> 数组
匹配所有没有子元素(包括文本内容)的元素
:parent 返回: <jQuery对象> 数组
匹配包含子元素(包含文本内容)的所有元素
:contains(text) 返回: <jQuery对象> 数组
匹配所有含有text的元素
:hidden 返回: <jQuery对象> 数组
匹配所有隐藏的元素,包含属性type值为hidden的元素
:visible 返回: <jQuery对象> 数组
匹配所有非隐藏的元素

子元素滤镜

E:nth-child(index/even/odd/equation) 返回: <jQuery对象> 数组
匹配所有E在其父元素下满足(index/even/odd/equation)条件的集合。注:下标从1开始
E:first-child 返回: <jQuery对象> 数组
匹配所有E在其父元素下是第一个子元素的集合。例 如:HTML(<div><p id="p1"></p></div><div><p id="p2"></p><p id="p3"></p></div>"),使用$("p:first-child"),选取:<p id="p1"></p><p id="p2"></p>
E:last-child 返回: <jQuery对象> 数组
匹配所有E在其父元素下是最后一个子元素的集合。例如:同上的HTML,使用$("p:last-child"),选取:<p id="p1"></p><p id="p3"></p>
E:only-child 返回: <jQuery对象> 数组
匹配所有E是其父元素的唯一子元素的集合。例如:同上的HTML,使用$("p:only-child"),选取:<p id="p1"></p>

表单滤镜

:input 返回: <jQuery对象> 数组
匹配所有的input、textarea、select、button
:text 返回: <jQuery对象> 数组
匹配文本域。注:在IE浏览器下,选择的对象是所有type属性为text的元素,在非IE浏览器下,选择的对象是input元素type属性为text的元素
:password 返回: <jQuery对象> 数组
匹配密码域。注:在IE浏览器下,选择的对象是所有type属性为password的元素,在非IE浏览器下,选择的对象是input元素type属性为password的元素
:radio 返回: <jQuery对象> 数组
匹配单选按钮。注:在IE浏览器下,选择的对象是所有type属性为radio的元素,在非IE浏览器下,选择的对象是input元素type属性为radio的元素
:checkbox 返回: <jQuery对象> 数组
匹配复选框。注:在IE浏览器下,选择的对象是所有type属性为checkbox的元素,在非IE浏览器下,选择的对象是input元素type属性为checkbox的元素
:submit 返回: <jQuery对象> 数组
匹配提交按钮。注:在IE浏览器下,选择的对象是所有type属性为submit的元素,在非IE浏览器下,选择的对象是input元素type属性为submit的元素和button元素type属性为空或为submit的元素
:image 返回: <jQuery对象> 数组
匹配图像域。注:在IE浏览器下,选择的对象是所有type属性为image的元素,在非IE浏览器下,选择的对象是input元素type属性为image的元素
:reset 返回: <jQuery对象> 数组
匹配重置按钮。注:在IE浏览器下,选择的对象是所有type属性为reset的元素,在非IE浏览器下,选择的对象是input或button元素type属性为reset的元素
:button 返回: <jQuery对象> 数组
匹配按钮。注:在IE浏览器下,选择的对象是所有type属性为button的元素和元素名为button的元素,在非IE浏览器下,选择的对象是input元素type属性为button的元素和元素名为button的元素
:file 返回: <jQuery对象> 数组
匹配文件域。注:在IE浏览器下,选择的对象是所有type属性为file的元素,在非IE浏览器下,选择的对象是input元素type属性为file的元素
:enabled 返回: <jQuery对象> 数组
匹配所有可用的元素。注:即:not(:disabled),参考:disabled的注释
:disabled 返回: <jQuery对象> 数组
匹配所有禁用的元素。注:在非IE浏览器下,选择的对象是禁用的表单元素
:checked 返回: <jQuery对象> 数组
匹配所有被选中的表单。注:在IE浏览器下,选择的对象是含有checked属性的所有元素
:selected 返回: <jQuery对象> 数组
匹配所有选择的表单。注:在IE浏览器下,选择的对象是含有selected属性的所有元素

属性滤镜

[attribute] 返回: <jQuery对象> 数组
匹配拥有attribute属性的元素
[attribute=value] 返回: <jQuery对象> 数组
匹配属性attribute为value的元素
[attribute!=value] 返回: <jQuery对象> 数组
匹配属性attribute不为value的元素
[attribute^=value] 返回: <jQuery对象> 数组
匹配属性attribute的值以value开始的元素
[attribute$=value] 返回: <jQuery对象> 数组
匹配属性attribute的值以value结尾的元素
[attribute*=value] 返回: <jQuery对象> 数组
匹配属性attribute的值包含value的元素
[selector1][selector2][selectorN] 返回: <jQuery对象> 数组
匹配满足属性选择器selector1、selector2、selectorN的元素

[CSS]点这个链接后只执行Js函数页面不作任何跳转和刷新的改变

mikel阅读(616)

最近用Ajax发现个问题,异步执行链接的onclick事件后,如果href=“#”总是刷新页面,结果总是定位不到当前点击的链接,也就是:“点这个链接后只执行Js函数页面不作任何跳转和刷新的改变.”
影响用户体验,于是搜了一下,如下代码
代码的意思就是,只是将鼠标的样式改为手型,但是根本就没有链到任何页面包括本身,其实很简单,如果不想链接到什么页面,不写href属性就行了,去掉style=”cursor:hand”也可以

<a style="cursor:hand" value=&#39;"&rs("iId")&"&#39; onClick=&#39;Smart("&rs("iId")&");&#39;>"&rs("sDescription")&"</a>  "

[MVC]ASP.NET MVC: 用db4o来做TempDataProvider(另附一个泛型的R

mikel阅读(802)

本文地址:http://www.cnblogs.com/QLeelulu/archive/2008/09/19/1294469.html
本文作者:Q.Lee.lulu
本文首发博客园 ,4MVC同步更新。本文示例基于ASP.NET MVC framework (Codeplex Preview 5) 。

关于db4o:

db4o是一种纯对象数据库,相对于传统的关系数据库+ORM,db4o具有以下好处:
1)以存对象的方式存取数据(废话~~,不过你考虑一下完全以对象的方式去考虑数据的存取对传统的数据库设计思维来说是多么大的颠覆);
2)无需数据库服务器,只需要一个数据文件,且dll大小仅为300多k,非常适合作为嵌入式数据库;
3)提供Query By Sample, Native Query和Simple Object DataBase Access(SODA)三种方式进行数据查询,操作简便且功能强大,和SQL说byebye。

以上为引用别人的介绍,目前最新的版本为7.5,支持LINQ语法。要使用db4o只需要在项目中引入db4o的DLL就可以,并不需要安装服务器端(类似于Access的文件型数据库)。

 

ASP.NET MVC的TempData用于在各个控制器Action间传输一些临时的数据,相信大家都看过“在ASP.NET页面间传值的方法有哪几种”这个面试 题,TempData的作用差不多就是这样。TempData默认是使用Session来存储临时数据的,虽然TempData中存放的数据只一次访问中有效,一次访问完后就会删除了的。但很多朋友还是对于将数据存放在Session表示担心,毕竟Session的资源宝贵啊。

使用db4o来存储TempData中的数据是一个不错的选择。之前看到有说用db4o来做中间层数据缓存,当时不是很明白,现在放到这里来想一想,就阔然开朗了。

ASP.NET MVC提供了一个ITempDataProvider的接口:

image

只要实现这两个方法,就可以实现我们的TempDataProvider了。ASP.NET MVC Preview 5 默认还提供了一个CookieTempDataProvider,在Microsoft.Web.Mvc命名空间下。

在这里我们先建一个TempObject的类来表示临时数据,因为TempData是跟用户对应的(想想Session),所以在这个对象中需要一个标识符标识当然用户。在这里我们就使用SessionId来标识吧。TempObject类的代码如下:

 

TempObject

 

 然后我们实现ITempDataProvider的两个方法,代码有注释,就不说了。代码如下:

public class db4oTempDataProvider : ITempDataProvider
{
    
/// <summary>
    
/// 实现接口的获取TempData方法
    
/// </summary>
    
/// <param name="controllerContext"></param>
    
/// <returns></returns>

    public virtual IDictionary<stringobject> LoadTempData(ControllerContext controllerContext)
    
{
        HttpContextBase httpContext 
= controllerContext.HttpContext;
        
if (httpContext.Session == null)
        
{
            
throw new InvalidOperationException("db4oTempDataProvider: SessionStateDisabled");
        }

        
//如果用户的Session没有任何数据,则每次请求的SessionId都是一个新的ID。
        
//只好出此下策,在Session附加一点数据。
        httpContext.Session["db4oTempDataProvider"= 1

        
//使用SessionId来标识当前用户
        string sessionId = httpContext.Session.SessionID; 

        
//从db4o数据库中取出对象
        TempObject temp = Db4oHelper.GetTempObject(sessionId); 

        
// 清理垃圾数据。想想你就会明白为什么会有垃圾数据了.
        
// 当前时间的30分钟以前创建的数据都认为是垃圾数据。
        
// 我也不知道多少时间合适,反正Session的默认过期时间是30分钟。
        Db4oHelper.CleanUp(); 

        
if (temp != null && temp.TempObjects != null)
        
{
            
//取出临时数据后,将数据删除,即TempData数据只被访问一次即删除
            Db4oHelper.DelTempObject(sessionId); 

            
return temp.TempObjects as Dictionary<stringobject>;
        }
 

        
return new Dictionary<stringobject>(StringComparer.OrdinalIgnoreCase);
    }

    
/// <summary>
    
/// 实现接口的保存TempData方法
    
/// </summary>
    
/// <param name="controllerContext"></param>
    
/// <param name="values"></param>

    public virtual void SaveTempData(ControllerContext controllerContext, IDictionary<stringobject> values)
    
{
        HttpContextBase httpContext 
= controllerContext.HttpContext;
        
if (httpContext.Session == null)
        
{
            
throw new InvalidOperationException("db4oTempDataProvider: SessionStateDisabled");
        }
 

        TempObject temp 
= new TempObject(httpContext.Session.SessionID);
        temp.TempObjects 
= values; 

        
//将TempData保存到数据库
        Db4oHelper.SaveTempObject(temp);
    }

}
 

 

附Db4oHelper的代码:

Db4oHelper

到这里我们已经实现了自己的TempDataProvider,但是怎么替换掉系统默认的SessionStateTempDataProvider呢?我们可以在Controller中进行替换,Controller提供了一个TempDataProvider的属性。我们写一个BaseController,在这里进行替换,然后让所后的Controller都继承自这个Controller就可以了。

public class BaseController : Controller
{
    
public BaseController()
    {
        
//将当前的TempDataProvider 修改为 db4oTempDataProvider。
        this.TempDataProvider = new db4oTempDataProvider();
    }
}

 

或许还有其他的更好的方法可以对全局进行替换?可以在Application_Start中进行这个操作?如果你知道,麻烦告诉我。 ^_^

 

完了测试了一下,貌似性能不咋的。也罢,大家当作是学习一下怎样实现一个TempDataProvider。不知是否我的数据库操作部分有问题?还是文件数据库本身读写慢?

对于db4o,有几个问题想请教一下:
1、不知道并发处理能力如何?
2、在这里用的单实例打开连接,并且操作完了都关闭连接,不知道这样处理是否合适?或者该怎样才能更好的管理这个数据库连接,才能更好的处理并发状况?

 

泛型的RedirectToAction方法

写过ASP.NET MVC代码的朋友应该发现,在Action中如果想要Redirect到另一个Action去,则我们或许会写如下的代码:

//跳转到HomeController中的Index Action
return RedirectToAction("Index""Home"); 

或者

//跳转到HomeController中的Index Action
return RedirectToRoute(new { controller = "Home", action = "Index" }); 

(或者你有其他好的办法我不知道?)

可以看到这里Controller和Action的名称都是用字符串来写的,对于代码维护和重构,这是不可想象的。所以反射了一下M$的代码,写了一个泛型的RedirectToAction方法,我们可以把这个方法写到前面提到的BaseController中去:

 

/// <summary>
/// 重定向到指定的Controller中的Action
/// </summary>

public RedirectToRouteResult RedirectToAction<T>(Expression<Action<T>> action) where T : Controller
{
    MethodCallExpression body 
= action.Body as MethodCallExpression;
    
if (body == null)
    
{
        
throw new InvalidOperationException("Expression must be a method call");
    }

    
if (body.Object != action.Parameters[0])
    
{
        
throw new InvalidOperationException("Method call must target lambda argument");
    }

    
string name = body.Method.Name;
    
string str2 = typeof(T).Name;
    
if (str2.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
    
{
        str2 
= str2.Remove(str2.Length  1010);
    }

    RouteValueDictionary values 
= LinkBuilder.BuildParameterValuesFromExpression(body) ?? new RouteValueDictionary();
    values.Add(
"controller", str2);
    values.Add(
"action", name); 

    
return new RedirectToRouteResult(values);
}

 

使用示例:

return RedirectToAction<HomeController>(h => h.Index());

这个返回的是一个RedirectToRouteResult,跟我们平时WebForm中的Redirect()一样是重定向到另一个URL,产生一个新的请求的。所以如果你有一个Action为:

public ActionResult Cpu(CPU cpu)
{
    ViewData[
"Cpu"= cpu;
    
return View();
}

那么你不可以如下这样调用:

return RedirectToAction<HomeController>(h => h.Cpu(cpu));

如果你需要这样做,你应该写一个ModelBinder,并重写你要传递的参数对象(在这里是CPU)的ToString()方法。具体请参见leven(神鱼)重典的Blog。

完。Enjoy!最后附上DEMO代码:TempDataProviderDemo.rar

[Json]MVC JSON - JsonResult and jQuery

mikel阅读(914)

The latest release of the MVC framework provides the JsonResult for Controller actions.  I was surprised that I did not find a weatlh of examples for usage so I figured it shouldn't be too hard to get a decent example going.  It turns out, it was even easier than I anticipated.  I wanted to create an example where I would invoke an AJAX call to dynamically populate a dropdown list. 

jQuery has recently received a huge surge of interest of the ASP.NET MVC community so I've been getting up to speed on it myself.  I am quickly turning into a true believer and I've been impressed not only with how few lines of JavaScript it takes me to get things done but also how (relatively) easy it was to learn.  In addition to numerous examples on the jQuery web site I also recommend jQuery In Action.

Getting an AJAX request with JQuery and JSON in MVC is actually pretty simple.  The first step is to have a Controller action that returns a JsonResult:

   1:  public JsonResult GetStateList()
   2:  {
   3:      List<ListItem> list = new List<ListItem>() {
   4:          new ListItem() { Value = "1", Text = "VA" },
   5:          new ListItem() { Value = "2", Text = "MD" },
   6:          new ListItem() { Value = "3", Text = "DC" }
   7:      };
   8:      return this.Json(list);
   9:  }

Here I'm using the System.Web.Mvc.ListItem class (which is used as items in the SelectList) to simply return a contrived list of US states to populate a dropdown list.  All I have to do is call the Json() method passing in my object and it will automatically be serialized to JSON.  When the request is made the AJAX call can be seen in the Web Development Helper which is an invaluable tool to any AJAX development:

Notice the "application/json" in the request header and the textual representation of the JSON that is being returned from my JSON controller action.

The JQuery to make this happen is quite succinct:

   1:  <script type="text/javascript">
   2:  $(function() {
   3:      $('#btnFillList').click(function() {
   4:          $.getJSON("/Home/GetStateList", null, function(data) {
   5:              $("#stateList").fillSelect(data);
   6:          });
   7:       });
   8:       
   9:       $('#btnClearList').click(function() {
  10:          $("#stateList").clearSelect();
  11:       });
  12:  });
  13:  </script>

Notice on line #4 the use of the $.getJSON() JQuery method.  Then I've simply written a re-usable jQuery method called fillSelect() which will work on the JSON format returned by the ListItem class returned by my controller action:

   1:  $.fn.clearSelect = function() {
   2:      return this.each(function() {
   3:          if (this.tagName == 'Select')
   4:              this.options.length = 0;
   5:      });
   6:   } 
   7:   
   8:  $.fn.fillSelect = function(data) {
   9:      return this.clearSelect().each(function() {
  10:          if (this.tagName == 'Select') {
  11:              var dropdownList = this;
  12:              $.each(data, function(index, optionData) {
  13:                  var option = new Option(optionData.Text, optionData.Value);
  14:                  
  15:                  if ($.browser.msie) {
  16:                      dropdownList.add(option);
  17:                  }
  18:                  else {
  19:                      dropdownList.add(option, null);
  20:                  }
  21:              });
  22:          }
  23:      });
  24:   }

On line #13 above you'll see the strongly-typed "Text" and "Value" properties that I have the luxury of using because of the native JSON serialization into objects.

The complete code sample can be downloaded here.  It's barely 50 lines of code in all.

[Jquery]使用Jquery应用到Asp.net ajax中时3个误区应该避免

mikel阅读(680)

Ajax中使用json这个轻量级数据类型通信的好处相信大家已经很清楚,考虑到安全问题,ASP.NET Ajax的webService使用json,应该防止Json Hijacking。因此通常我们的做法是在使用Post请求式,并将请求的content-type设置成application/json; charset=utf-8。但客户端如果你使用的是JQuery,有三个细节问题是我们应该注意的:
      1 :如果我们Post时没有任何数据传给服务端,请指定Data:{} 如:
   
Code
1 $.ajax({
2  type: "POST",
3  url: "PageMethod.aspx/PageMethodName",
4  data: "{}",//注意这里不可省。
5  contentType: "application/json; charset=utf-8",
6  dataType: "json"
7 });
  这是因为在IIS中post请求时Content —Length是必须提供的,即使没用任何Post Data.Content-Length也应该设为0,但这样的话JQuery不会自动设置Header,除非请求中包含post Data。而ASP.NET Ajax的json传输,又要求post方式,因此我们不能改变他的请求方式。简便的解决法案就是在请求中给定一个空的json 对象。以符合IIS的要求,此时Content-Length为2。这时在服务端我可以完全忽略这个为空的参数,并处理相应的请求。
    2:当post data 不为空时。我们应该避免在beforeSend事件里设置RequestHeader。
    如一点所述的范例post data 为空时,既然JQuery不能自动设置Header,我们能否手工帮他设置呢?答案时是
肯定的。这时我们是在beforeSend事件中设置的。如代码所示(请注意:必须设置为application/json否则webservice
时不会返回json。这也是出于安全的考虑)。
Code
1 $.ajax({
2  type: "POST",
3  url: "WebService.asmx/WebMethodName",
4  beforeSend: function(xhr) {
5    xhr.setRequestHeader("Content-type",
6                          "application/json; charset=utf-8");
7  },
8  dataType: "json"
9 });
    但时此时问题又来了,在IE中XmlHttpRequst的setRequestHeader不时直接完全的设置RequstHeader。而是
在已有的基础上附加setRequestHeader参数所指定的以形成新的header。这样的话,在jQuery会在包含Post Data请求
的header中自动设置content-type为默认的application/x-www-form-urlencoded ,而在beforeSend又会被重新追
加一个application/json; charset=utf-8。此时Content-Type变成了 application/x-www-form-urlencoded,
application/json; charset=utf-8(在ff会重新设置)。很显然这个content-type不为Asp.net Ajax所接受。webservice
不会返回任何json。因此包含post data时建议使用下列方式保证返回的为json
Code
$.ajax({
  type: "POST",
  url: "WebService.asmx/WebMethodName",
  data: "{'fname':'dave', 'lname':'ward'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});
  3:注意区分json对象和json形式的字符串。
  看看下面代码:
Code
$.ajax({
  type: "POST",
  url: "WebService.asmx/WebMethodName",
  data: {'fname':'dave', 'lname':'ward'},
  contentType: "application/json; charset=utf-8",
  dataType: "json"
});
咋一看没什么问题,想当然的认为data会乖乖的post给服务端。但实际上这是不正确的。请仔细看此时data时json
表示的对象。此时Json表示的对象会被jQuery序列化。如上述例子data将是fname=dave&lname=ward。再看如下:
Code
1 $.ajax({
2  type: "POST",
3  url: "WebService.asmx/WebMethodName",
4  data: "{'fname':'dave', 'lname':'ward'}",
5  contentType: "application/json; charset=utf-8",
6  dataType: "json"
7 });
这时data才是我们期望的。其形式:{'fname':'dave', 'lname':'ward'}。小小语义的改变就可以造成如此大的不同。
因此,我们在编程过程中应该特别注意。以免浪费时间。
注:有关细节可以参看3 mistakes to avoid when using jQuery with ASP.NET AJAX ,有更详细的说明。我只是
重新用中文简要的重述一下其中讲到的问题。
原文出处:http://www.cnblogs.com/mingxuan

[Json]Jquery解析Asp.net MVC的JsonResult格式数据

mikel阅读(1019)

As I was looking around for ways to enable Ajax in the current ASP.NET MVC release I found a couple of things that I found pretty useful and thought I should share.

The J in Ajax (JQuery)

The muscle behind the actual asynchronous calls comes from JavaScript. I looked around at a bunch of existing JavaScript libraries and settled on JQuery because of the way it leverages existing CSS knowledge. The three things that the library should do easily are:

  1. Help me easily display an "updater" to let user know something is happening (i.e. loading data),
  2. Assist in making the actual Ajax call without any hassle,
  3. and, most importantly, let me get 1 and 2 working without headaches.

Here is how jQuery helps in the three cases:

  1. The "updater":
    $('#updater').show();
    $('#updater').hide();
    Notice the way jQuery uses the standard CSS id selector. Could it be any easier?
  2. JQuery has the following Ajax calls available in its library:
    object.load( )
    $.get( )
    $.post( )
    $.getJSON( )
    This takes away (hides) all of the XmlHttp object nonsense from the whole Ajax call.
  3. See 1 and 2

ASP.NET MVC

There are tons of good posts/tutorials on exactly how the ASP.NET MVC model works so I will not attempt to get into it too much here. The most important thing to know is that there are three things working together:

  1. The Controller,
  2. The Model, and
  3. The View

The controller handles all of the requests, asks the model for data, and then instructs the view to present the data (if any) returned.

Routes

One of the neat things about the MVC framework is the notion of routes. The default route setup is as follows:

   1:  routes.MapRoute(
   2:          "Default",                                              // Route name
   3:          "{controller}/{action}/{id}",                           // URL with parameters
   4:          new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
   5:  );

This simply means that, from the root of your web app, whenever a URL of the form http://root/foo/baz/bar is presented, the routing engine will call the foo controller with the baz action while supplying it with the bar id.

Some Code

Enough explanation, now to some code!

The Model

Since this is not an exercise in using the database, I created a simple Model class for students:

   1:  public class Student
   2:  {
   3:     public string FirstName { get; set; }
   4:     public string LastName { get; set; }
   5:     public int StudentId { get; set; }
   6:          
   7:     public static IQueryable<Student> GetStudentDataList()
   8:     {
   9:        return new List<Student>() 
  10:        {
  11:           new Student { FirstName = "John", LastName = "Smith", StudentId = 1},
  12:           new Student { FirstName = "Susan", LastName = "Connor", StudentId = 2},
  13:           new Student { FirstName = "Bryan", LastName = "Jones", StudentId = 3},
  14:           new Student { FirstName = "Lucy", LastName = "Vargas", StudentId = 4},
  15:           new Student { FirstName = "Robert", LastName = "Jimenez", StudentId = 5},
  16:           new Student { FirstName = "Seth", LastName = "Juarez", StudentId = 6},
  17:           new Student { FirstName = "David", LastName = "Meeks", StudentId = 7},
  18:           new Student { FirstName = "Olivia", LastName = "Rassmusen", StudentId = 8},
  19:           new Student { FirstName = "Viola", LastName = "Masterson", StudentId = 9},
  20:           new Student { FirstName = "Russel", LastName = "Jones", StudentId = 10}
  21:        }
  22:        .AsQueryable<Student>();
  23:     }
  24:  }

This simply creates a new list of Students and returns them as an IQueryable.

The Controller

Since I want to only pass JSON serialized objects over the wire when making the Ajax calls, there is a handy return type for the action in the controller called JsonResult:

   1:  public JsonResult Find(string name)
   2:  {
   3:     // To simulate "wait"
   4:     System.Threading.Thread.Sleep(1500);
   5:          
   6:     return new JsonResult
   7:     {
   8:        Data = (from student in Student.GetStudentDataList()
   9:                where student.LastName.StartsWith(name)
  10:                select student).ToArray<Student>()
  11:     };
  12:  }

This will serialize the data out in the JSON format. Now for the actual interesting part:

The View

The html for this example is VERY simple:

   1:  <div id="query">
   2:        <%= Html.TextBox("textSearch") %>&nbsp;
   3:        <a href="#" id="linkFind">Find</a>&nbsp;&nbsp;&nbsp; 
   4:        <span class="update" id="updater">
   5:              <img src="<%= AppHelper.ImageUrl("indicator.gif") %>" alt="Loading" />
   6:              &nbsp;Loading...&nbsp;&nbsp;&nbsp;
   7:        </span>
   8:  </div>
   9:   <div class="label">Students:</div> 
  10:  <div id="studentList"></div>

There is a search box, a link, and update panel, and a div (studentList) that will be populated by the Ajax call. This is where the magic of the routing engine coupled with the JQuery Ajax call comes together:

 

   1:  $(document).ready(
   2:     function()
   3:     {
   4:        // Hide update box
   5:        $('#updater').hide();
   6:                  
   7:        var retrieveData = function(path,  query,  funStart,  funEnd, funHandleData)
   8:        {
   9:           // for displaying updater
  10:           funStart();
  11:                          
  12:           // retrieve JSON result
  13:           $.getJSON(
  14:              path,
  15:              { name : query },
  16:              function(data)
  17:              {
  18:                 // handle incoming data
  19:                 funHandleData(data);
  20:                 // for hiding updater
  21:                 funEnd();
  22:              }
  23:           );
  24:        };
  25:                  
  26:        // adding handling to find link
  27:        $('#linkFind').click(
  28:           function(event)
  29:           {
  30:              event.preventDefault();
  31:              retrieveData(
  32:                 // mvc route to JSON request
  33:                 '/Student/Find/', 
  34:                 // query from textbox
  35:                 $('#textSearch')[0].value, 
  36:                 // function to show updater
  37:                 function() { $('#updater').show(); }, 
  38:                 // function to hide updater
  39:                 function() { $('#updater').hide(); },
  40:                 // retrieving the data
  41:                 function(data)
  42:                 {
  43:                    // clear students (if any)
  44:                    $('#studentList > div').remove();
  45:                    // add students
  46:                    for(s in data)
  47:                    {
  48:                       var student = data[s];
  49:                       $('#studentList').append('<div>(' +  student.StudentId ... you get the idea                 
  50:                     }
  51:                 }
  52:              );
  53:            }
  54:         );
  55:      }
  56:  );

The retrieveData function uses the JQuery $.getJSON call to retrieve the data. It takes as arguments the path to the controller (remembering routes), the argument (in this case the query) that the controller action expects, as well as a couple of functions. These functions will handle the cases where the  request is started, the request is ended, and what to do with the data that is returned. Subsequently we add the event handler to the link that initiates the find request. Notice that we are passing in '/Student/Find/' as the path since we are using the Find action on the StudentController. The argument is passed in from the search text box. This sets into motion the asynchronous request to the controller. The controller then returns a JSON serialized array of Student objects. Once the data is received, the studentList div is then cleared and repopulated.

Screenshot

The request:

request

The response:

response

Conclusion

Hopefully this has been helpful! It was fun putting everything together. Feel free to send me an email or leave a comment on this post if there are any suggestions/comments.

Code

[Flex]Learning Flex 3: Getting up to Speed with Ri

mikel阅读(737)

Download Learning Flex 3: Getting up to Speed with Rich Internet Applications
下载 Learning Flex 3: Getting up to Speed with Rich Internet Applications

简介 Book Description
How soon can you learn Adobe Flex 3? With this book's unique hands-on approach, you will be able to tinker with examples right away, and create your own Rich Internet Applications with Flex within the first few chapters. As you progress, you learn how to build a layout, add interactivity, work with data, and deploy your applications to either the Web or the desktop.
Learning Flex 3 offers step-by-step instructions that are clear and concise, along with tips and tricks that author Alaric Cole has gathered after years of using Flex and teaching it to fellow developers at Yahoo! You'll understand how Flex works, how to use the MXML markup language and work with ActionScript, how to deploy RIAs to the desktop using Adobe AIR, and much more.
Whether you're a beginner, or an experienced web developer coming to Flex from another platform, Learning Flex 3 is the ideal way to learn how to:
* Set up your environment with FlexBuilder and Eclipse
* Create a new Flex project
* Use the different design views in Flex
* Write code with MXML
* Lay out your Flex application
* Embed images and graphics
* Build a user interface
* Add interactivity with ActionScript
* Handle user input
* Move, display, and collect data
* Add custom components with MXML
* Add sound effects, filters, and transitions
* Style your applications with CSS, skins, and themes
* Deploy applications to the Web, or to the desktop using Adobe AIR
Also included are brief explanations of objects, classes, components, properties, methods, types, and other Flex attributes. You will find that Learning Flex 3 is not only the most complete tutorial for Flex, it's also the quickest way to get going with the latest version of this powerful framework.
目录 Table of Contents
Chapter 1
Getting Up to Speed 1
What Is Flex? 1
What about AIR? 4
Where Flex Fits 5
Why Use Flex? 6
How Flex Compares to Other Technologies 8
When Not to Use Flex 11
Summary 12
Chapter 2
Setting Up Your Environment 13
Using Alternatives to Flex Builder 13
Introducing Flex Builder and Eclipse 14
Running Your First Application 16
Summary 21
Chapter 3
Using Design Mode 23
A Blank Slate: Your Canvas 23
Adding Components to the Application 24
Moving Components Around 24
Exploring Common Components 25
Modifying Properties Directly 28
Summary 36
Chapter 4
Using Source Mode37
What Design Mode Does 37
Anatomy of a Flex Application 38
Components Added in Source Mode 39
Code Completion 40
MXML in Depth 40
Summary 46
Chapter 5
Learning the Basics of Scripting 47
Getting Ready 47
Inline ActionScript 48
Dot Notation 48
Assignment 49
Functions 50
Variables 53
Data Types53
Objects 55
Classes 56
MXML and ActionScript Work Together 57
ActionScript’s Relationship with MXML 58
Comments? 61
Summary 61
Chapter 6
Adding Interactivity with ActionScript 63
Understanding Events63
Handling Events Inline64
Using Event Constants67
Making Things Happen 67
Debugging for Kicks 71
Summary 76
Chapter 7
Using Data Binding77
What Is Data Binding? 77
How to Use It 78
Implementing Two-Way Bindings83
Storing Complex Data83
Creating Bindable Variables in ActionScript 85
Determining When Data Binding Isn’t Appropriate 86
Putting Data Binding to Work for You 87
Summary 91
Chapter 8
Laying Out Your Applications93
Types of Layouts93
The Display List 95
Sizing 99
Layout Container Options101
Advanced Containers 103
Layout Controls 106
Alignment 108
Constraints-Based Layout 109
Summary115
Chapter 9
Creating Rich Forms 117
Preparing the Application 117
Validating Data120
Restricting Input 131
Formatting Data for Display 132
Summary136
Chapter 10
Gathering and Displaying Data 137
Using List Controls 137
Using XML Data 142
Implementing List Selection 149
Connecting to Search Results 150
Dragging and Dropping in Lists153
Using Inline Item Renderers 154
Exploring Other Types of Service Components 156
Summary158
Chapter 11
Controlling Flow and Visibility 159
Controlling Visibility 159
Navigation Components 160
Creating a Photo Gallery Application 164
Summary174
Chapter 12
Working with View States 175
Scenarios for States 175
Creating New States176
Modifying State Properties, Styles, and Events 177
Adding Components 179
Putting States to the Test 183
Summary196
Chapter 13
Applying Behaviors, Transitions, and Filters 197
Behaviors197
Common Effects and Their Properties204
Sound Effects 209
States Made More Interesting 211
Filters 215
Summary218
Styling Applications 219
Using Inline Styles 219
Using Style Sheets 223
Embedding Assets 230
Skinning 233
Using Themes 235
Summary238
Chapter 15
Deploying Your Application 239
Deploying to the Web 239
Deploying to the Desktop251
Summary264
作者 About the Author
Alaric Cole has been working with Flash technologies since the introduction of ActionScript. Once it came on the scene, he's been focused primarily on Flex development, creating enterprise applications with rich data visualization, interactive media, and advanced user interface components. Pushing Flex beyond its comfort zone, he has worked with Adobe to discover ways to improve the technology.
A leader in the industry, Alaric has spoken at conferences such as Adobe MAX and 360|Flex, and has contributed a number of open-source components to the Flex community. He uses Flex in his daily work at Yahoo!, leading development and consulting on projects across the company.
下载 Download
http:
from easy-share
from depositfiles
from rapidshare ( Password default: netbks.com )

[Flex]The Essential Guide to Open Source Flash Dev

mikel阅读(781)

Download The Essential Guide to Open Source Flash Development
下载 开源Flash开发本质

简介 Book Description
The Essential Guide to Open Source Flash Development is a practical development guide to creating Flash applications with open source Flash tools and workflows. You will walk away with an understanding of what tools will best suit your current situation, making your development easier and more productive, and with the knowledge of how to install and set up some of the best tools available, including the following:
* Papervision3D: to create 3D in Flash
* Red5: to stream video over the internet
* SWX: to build data-driven mashups and mobile apps
* Fuse: to make ActionScript animation a cinch
* Go: to build your own animation tools in ActionScript 3.0
* haXe: to create Flash files and more
* AMFPHP: to communicate between Flash and php
Open source Flash has been a revolution for Flash and has made a major impact on how people build Flash content. The open source tools available expand on Flash's existing tool set, enabling you to perform such tasks as easily create full 3D in Flash or hook up to an open source video-streaming server. Many of these useful tools are powerful yet lack documentation. this book explains in step-by-step detail how to use the most popular open source Flash tools.
If you want to expand your Flash tool set and explore the open source Flash community, then this book is for you. If you already use some open source Flash tools, then you will find this book a useful documentation resource as well as an eye-opener to the other tools that are available.
INTRODUCTION
Welcome to The Essential Guide to Open Source Flash Development. The concept of “open
source” has been around for a while now, and most people are familiar with its meaning, but
how does that relate to Adobe Flash, which is a traditionally closed platform? When people talk
about open source Flash, they can mean any number of things—an ActionScript library, a code
editor, a new messaging format—what’s important is that the project extends or supports Flash
and follows the open source methodology. One of the leading lights in the open source Flash
world is Aral Balkan, and he put together the OSFlash.org website that brought together all of
the existing disparate open source Flash projects into one focused community. This community
blossomed to produce some incredible projects that not only expanded the possibilities of what
Flash can do but also completely altered people’s perceptions of what Flash meant as a tool and
how SWF files could be created.
This book is a collection of some of the best of those projects. We’ve collected projects that run
the whole gamut of the open source Flash world so you can get an idea of just what sort of
power is available to you. Alongside the project-specific chapters, we’ve also gone into a lot of
detail on how these projects can be integrated to make a full open source SWF workflow or
how you can pick and choose the projects that you want to use to expand your existing workflow.
After all, it’s one thing to experiment with these projects at home, but their real use is to
empower your current workflow to make Flash a bigger, better, faster, and more fun field to
work within.
Adobe has also started an open source initiative (see http://opensource.adobe.com) that
already has some pretty exciting projects as part of it and is sure to see even more in the future.
This is great news for the open source Flash community. With Adobe’s dedication to opening up
its platform and more and more users becoming involved in open source projects, the future
looks pretty rosy for open source Flash development. There hasn’t been a better time than now
to dive in.
目录 Table of Contents
* Chapter 1 Introducing the World of Open Source Flash
* Chapter 2 Exploring Open Source Flash: What's Available
* Chapter 3 Preparing an Open Source Workflow
* Chapter 4 Using an Open Source Workflow
* Chapter 5 Testing and Debugging
* Chapter 6 Deploying Your Application
* Chapter 7 Using AMFPHP
* Chapter 8 Working with SWX: The Native Data Format for the Flash Platform
* Chapter 9 Using haXe
* Chapter 10 Fuse and GoASAP: Open Source Animation Tools
* Chapter 11 Using Papervision3D
* Chapter 12 Introducing Red5
* Chapter 13 Building Some Red5 Apps
作者 About the Author
Chris Allen,
Wade Arnold,
Aral Balkan,
Nicolas Cannasse,
John Grden,
Moses Gunesch,
Marc Hughes,
R. Jon MacDonald,
Andy Zupko
下载 Download
http:
from rapidshare ( Password default: netbks.com )

[JQuery]去除字符串中的所有空格

mikel阅读(746)

function IgnoreSpaces(Str){
var ResultStr = “”;
Temp=Str.split(” “); //双引号之间是个空格;
for(i = 0; i < Temp.length; i++) ResultStr +=Temp[i]; alert(ResultStr); return ResultStr; } [/code]

[JQuery]JQuery设置CSS的样式实例代码

mikel阅读(826)

<script language="javascript" type="text/javascript" src="../../Content/jquery-1.2.6.js"></script>
<script language="javascript" type="text/javascript">
//当前选中的Tab
var currentTab="";
//设置Tab样式
function Tab(id)
{   //删除前一个选中的样式
$(currentTab).removeClass("zprcOff");
$(currentTab).addClass("zprconrb");
//设置当前为选中
$(id).removeClass("zprconrb");
$(id).addClass("zprcOff");
//设置选中的ID为当前ID
currentTab=id;
}
//设置Tab的Click事件
function SetTab(id,setId)
{
$(id).click(function(){
Tab(setId);
});
}
$(document).ready(function(){
SetTab("#tab1","#tabset1");
SetTab("#tab2","#tabset2");
SetTab("#tab3","#tabset3");
SetTab("#tab4","#tabset4");
SetTab("#tab5","#tabset5");
currentTab="#tabset1";
Tab(currentTab);
});
</script>