ASP.NET MVC 异步调用

在ASP.NETMVC beta中我们可以使用Ajax.BeginForm, Ajax.ActionLink来进行Ajax调用,同样我们也可以使用一些支持Ajax 框架如jQuery来简化对ajax的调用。

1. ASP.NET MVC beta中内置了AJAX的支持,但是我们必须引入MicrosoftAjax.js, MicorsoftMvcAjax.js.

ASP.NET MVC 异步调用_第1张图片

2. 由于ASP.NET MVC已经集成了jQuery,所以我们也可以很方便的使用jQuery的Ajax功能

ASP.NET MVC 异步调用_第2张图片

上图的代码展示了前台的三种方式

(1)Ajax.BeginForm

这里涉及到如何附加表单之外的参数到远程,实际上我们只需要附加到post的url后就行了,例如把action改为AjaxGetJSON?name=jack,或者AjaxGetJSON/jack然后配置route就可以

  (2)  Ajax.ActionLink

附加参数和上面相同

  (3) jQuery.ajax

       参看上图的GetByJquery()函数

3.后台代码

第一个直接返回Json数据,第二个,第三个都是通过用户控件来返回Html.

 

  public JsonResult AjaxGetJSON(Personp)

  {

     Thread.Sleep(3000);

     returnthis.Json(p);

  }

 

  public ActionResult AjaxGetString()

  {

     Personp = new Person{ FirstName = "Bill", LastName = "Gates" };

     returnView("AjaxContent",p);

  }

 

  public ActionResult AjaxByJquery()

  {

     Personp = new Person{ FirstName = "Bill", LastName = "Gates" };

     returnView("AjaxContent", p);

  }

 

4. AjaxContent用户控件内容

 ASP.NET MVC 异步调用_第3张图片

通过上面的方法,我们很容易模仿原来webservice方式的调用,把ajax的功能放到一个统一的controller里,比如叫AjaxServiceController.

 

 

 

这是第一使用Jquery实现城市三级数据联动的实例!之前本人没有使用过Jquery,在WebForm的开发过程中,很多时候用的是ASP.NET Ajax,ajaxPro+JavaScript,从未使用过JS框架,最近在学习ASP.NETMVC,在最新的发布版本中,已经集成了Jquery 1.3.1,自然,也要学一学!发现使用Jquery代码果然写得比原始JS优雅!只是语法和方法太多,现在还没弄熟,还需要时间来学习.....这次是第一次使用Jquery写客户端脚本,如果大家发现更好的实现方法,请给我留言!谢谢!

注明:ASP.NET MVC 1.0 ,作者:0x001;

View:

<script type="text/javascript">
    $(document).ready(function() {
        GetByJquery();
       $("#ddlProvince").change(function() { GetCity() });
       $("#ddlCity").change(function() { GetDistrict() });
    });
   
    function GetByJquery() {

       $("#ddlProvince").empty(); //清空省份SELECT控件

       $.getJSON("/ajax/GetProvinceList", function(data) {
            $.each(data,function(i, item) {
               $("<option></option>")
                   .val(item["ProvinceID"])
                   .text(item["ProvinceName"])
                   .appendTo($("#ddlProvince"));
            });
            GetCity();
        });     

    }

    function GetCity() {

       $("#ddlCity").empty(); //清空城市SELECT控件
        var url ="/ajax/GetCityList/"+ $("#ddlProvince").val();
        $.getJSON(url, function(data) {
            $.each(data,function(i, item) {
               $("<option></option>")
                   .val(item["CityID"])
                   .text(item["CityName"])
                   .appendTo($("#ddlCity"));
            });
           GetDistrict();
        });
    }

    function GetDistrict() {
        $("#ddlDistrict").empty();//清空市区SELECT控件
        var url ="/ajax/GetDistrictList/" + $("#ddlCity").val();
       
        $.getJSON(url, function(data) {
            $.each(data,function(i, item) {
               $("<option></option>")
                   .val(item["DistrictID"])
                   .text(item["DistrictName"])
                   .appendTo($("#ddlDistrict"));
            });
        });
    }

</script>
<table><tr><td><selectid="ddlProvince"/></td><td><selectid="ddlCity"/></td><td><selectid="ddlDistrict" /></td></tr></table>

Controller :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;

namespace MvcBBS.Controllers
{
    public class AjaxController : Controller
    {
        //
        // GET: /Ajax/

        ///<summary>
        /// 获取所有[省份]数据
        /// </summary>
        public ActionResultGetProvinceList()
        {
            if(!Request.IsAjaxRequest())
            {
               return Content("请不要非法方法,这是不道德的行为!");
            }

           BLL.Province bll = new MvcBBS.BLL.Province();
           List<MvcBBS.Model.S_Province> modellist = bll.GetProvinceList();

           return Json(modellist);
        }

        ///<summary>
        /// 获取某[省份]的所有[城市]数据
        /// </summary>
        public ActionResult GetCityList(intid)
        {
            if(!Request.IsAjaxRequest())
            {
               return Content("请不要非法方法,这是不道德的行为!");
            }
            BLL.Provincebll = new MvcBBS.BLL.Province();
           List<MvcBBS.Model.S_City> modellist = bll.GetCityList(id);
            returnJson(modellist);
        }

        ///<summary>
        /// 获取某[城市]的所有[市区]数据
        /// </summary>
        public ActionResultGetDistrictList(int id)
        {
            if(!Request.IsAjaxRequest())
            {
               return Content("请不要非法方法,这是不道德的行为!");
            }

           BLL.Province bll = new MvcBBS.BLL.Province();
           List<MvcBBS.Model.S_District> modellist = bll.GetDistrict(id);

           return Json(modellist);
        }

    }
}

我比较喜欢使用三层+工厂模式来读写数据,O/R Mapping不太适合我的要求!我们写的项目经常不是为了方便移植,而是选择明确的数据库,需要更高的性能,更强的业务逻辑!大家看到上面的代码,应该很熟悉,从数据库读数据到List<>中返回,并使有ASP.NET MVC内置的Json方法转换数据并Response.

DAL:    

// BLL,Model就不贴出来了!

using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using System.Collections.Generic;
using DBUtility;//请先添加引用

namespace MvcBBS.DAL
{
    public class Province
    {
        public Province()
        {}

        ///<summary>
        /// 获取所有省份数据
        /// </summary>
        /// <returns></returns>
        public List<Model.S_Province>GetProvinceList()
        {
           StringBuilder strSql = new StringBuilder();
           strSql.Append("SELECT ProvinceID,ProvinceName ");
           strSql.Append(" FROM S_Province ");
           List<Model.S_Province> modelList = new List<MvcBBS.Model.S_Province>();
           SqlDataReader dr =DbHelperSQL.ExecuteReader(strSql.ToString());           
            while(dr.Read())
            {
                Model.S_Province _model = new MvcBBS.Model.S_Province();
                _model.ProvinceID = int.Parse(dr["ProvinceID"].ToString());
                _model.ProvinceName = dr.GetString(1);
               modelList.Add(_model);
            }
            dr.Close();
            returnmodelList;
        }

        ///<summary>
        /// 获取某省份的所有城市数据
        /// </summary>
        /// <paramname="ProvinceID"></param>
        /// <returns></returns>
        public List<Model.S_City>GetCityList(int ProvinceID)
        {
           StringBuilder strSql = new StringBuilder();
           strSql.Append("SELECT CityID,CityName,ZipCode");
           strSql.Append(" FROM S_City ");
           strSql.Append(" WHERE ProvinceID=");
           strSql.Append(ProvinceID.ToString());

           List<Model.S_City> modelList = new List<MvcBBS.Model.S_City>();
           SqlDataReader dr = DbHelperSQL.ExecuteReader(strSql.ToString());
            while(dr.Read())
            {
               Model.S_City _model = new MvcBBS.Model.S_City();
               _model.CityID = int.Parse(dr["CityID"].ToString());
               _model.CityName = dr.GetString(1);
               _model.ZipCode = dr.GetString(2);
               _model.ProvinceID = ProvinceID;
               modelList.Add(_model);
            }
            dr.Close();
            returnmodelList;
        }

        ///<summary>
        /// 获取某城市的所有市区
        /// </summary>
        /// <paramname="CityID"></param>
        /// <returns></returns>
        public List<Model.S_District>GetDistrict(int CityID)
        {
           StringBuilder strSql = new StringBuilder();
           strSql.Append("SELECT DistrictID,DistrictName");
           strSql.Append(" FROM S_District ");
           strSql.Append(" WHERE CityID=");
           strSql.Append(CityID.ToString());

           List<Model.S_District> modelList = newList<MvcBBS.Model.S_District>();
           SqlDataReader dr = DbHelperSQL.ExecuteReader(strSql.ToString());
            while(dr.Read())
            {
               Model.S_District _model = new MvcBBS.Model.S_District();
               _model.DistrictID = int.Parse(dr["DistrictID"].ToString());
               _model.DistrictName = dr.GetString(1);
               _model.CityID = CityID;
               modelList.Add(_model);
            }
            dr.Close();
            return modelList;
        }
    }
}

 

你可能感兴趣的:(asp.net)