MVC DropDownList 利用Ajax联动

来源:互联网 发布:淘宝巨型猪笼草 编辑:程序博客网 时间:2024/04/27 02:06

页面代码:

[xhtml] view plaincopy
  1. <td style="text-align: right; width: 100px;">  
  2.     城市/区域:  
  3. </td>  
  4. <td style="width: 170px; text-align: left">  
  5.     <%= Html.DropDownListFor(m => m.City, new SelectList(Test.TestPersistence.TestDao.GetCodeDict(11), "Id", "Name"))%>  
  6.     <%= Html.DropDownListFor(m => m.Region, new SelectList(Test.TestPersistence.TestDao.GetCodeDict(1001), "Id", "Name"))%>  
  7. </td>  

javascript代码:ajax的

[javascript] view plaincopy
  1.     <mce:script type="text/javascript"><!--  
  2.         $(document).ready(function() {  
  3.             $("#City").change(function() {  
  4.                 var selec = $("#City").val();  
  5.                 $("#Region").get(0).options.length = 0;  
  6.                 $.getJSON("RegionByCity?pid=" + selec, { 'City': selec }, function(data) {  
  7.                     for (var i = 0; i < data.length; i++) {  
  8.                         $("#Region").append("<option value='" + data[i].Id + "'>" + data[i].Name + "</option>");  
  9.                     }  
  10.                 });  
  11.             });  
  12.         });                      
  13.       
  14. // --></mce:script>  

control的代码:

[c-sharp] view plaincopy
  1. public ActionResult RegionByCity()  
  2. {  
  3.     int pid = Convert.ToInt32(Request.QueryString["pid"]);  
  4.     CodeDao codeDao = new CodeDao();  
  5.     var codeList = codeDao.GetCodes(pid);  
  6.     if (Request.IsAjaxRequest())  
  7.     {  
  8.         return Json(codeList, JsonRequestBehavior.AllowGet);  
  9.     }  
  10.     else  
  11.     {  
  12.         return View("");  
  13.     }  
  14. }  

逻辑层: 

[c-sharp] view plaincopy
  1. public IList<Code> GetCodes(int pid)  
  2. {  
  3.     using (ISession session = sessions.OpenSession())  
  4.     {  
  5.         IQuery query = session.CreateQuery("from Code c where c.PId =:pid order by Id ");  
  6.         query = query.SetInt32("pid", pid);  
  7.         return query.List<Code>();  
  8.     }  
  9. }  


原创粉丝点击