我们在testmodel.cs中创建一个函数,以取得json数据,仍然使用tets表,包含两个字段:id和name。
复制代码 代码如下:
//jsondataarray
public static array getjsonarray(string name)
{
array data = null;
try
{
data = (from c in testdb.test
where c.name.contains(name)
select new { c.id, c.name }).toarray();
}catch(argumentnullexception ae)
{}
return data;
}
json数据,简单来说,即使用key-value数组形式的数据。然后按默认选项创建一个控制器,生成的控制器只有一个方法:index()。我们再创建一个方法,以供jquery调用。完成的代码如下:jquerycontroller.cs。注意:在mvc2.0中默认情况中禁止jquery调用服务器数据,所以必须在代码中增加访问权限:jsonrequestbehavior.allowget。
复制代码 代码如下:
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.mvc;
using mvcweb.models;
namespace mvcweb.controllers
{
public class jquerycontroller : controller
{
//
// get: /jquery/
public actionresult index()
{
return view();
}
public jsonresult findbyname(string name)
{
return json(testmodel.getjsonarray(name), jsonrequestbehavior.allowget);
}
}
}
然后在index()上按右键,按默认选项生成一个视图,可在views/jquery看到生成的代码:index.aspx,生成的代码非常简单,我们再插入script代码,完成如下:
复制代码 代码如下:
jquery
');
});
});
$('#updater').hide();
});
});
使用jquery实现ajax实例
搜索
loading...
id name
运行项目,在文本框中输入“t”,按“搜索”,在页面没有刷新的情况下显示出查询到的数据,如下图:
另外,在ajax开发中,还可以使用ajax的基础函数$.ajax进行调试,当出现错误时,可以打印错误信息。例如,对上述的调用可以用下面代码调试:
复制代码 代码如下: