ASP.NET MVC 中使用用户控件

周末加班,闲来无事,写篇博客,讲讲怎么在 ASP.NET MVC2中使用用户控件。首先我们新建一个用户控件,

ASP.NET MVC 中使用用户控件

我们命名为SelectGroup.ascx,代码如下


  1. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 
  2. <script language="javascript" type="text/javascript" src="<%=Url.Content("~/Areas/Util/Scripts/SelectGroup.js") %>"></script> 
  3. <div> 
  4.     <table> 
  5.         <tr> 
  6.             <td style="text-align:right"> 
  7.                 招生批次  
  8.             </td> 
  9.             <td> 
  10.                 <select id="admissionBatch" style="width: 150px"> 
  11.                 </select> 
  12.             </td> 
  13.             <td style="text-align:right; width:80px"> 
  14.                 学历层次  
  15.             </td> 
  16.             <td> 
  17.                 <select id="edcuationLevel" style="width: 150px"> 
  18.                 </select> 
  19.             </td> 
  20.             <td style="text-align:right; width:80px"> 
  21.                 专业名称  
  22.             </td> 
  23.             <td> 
  24.                 <select id="professional" style="width: 150px"> 
  25.                 </select> 
  26.             </td> 
  27.         </tr> 
  28.     </table> 
  29. </div> 

我们再编写其对应的控制器如下


  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.  
  7. namespace EducationManage.Areas.Util.Controllers  
  8. {  
  9.     using Utility.Json;  
  10.     using EducationManage.Areas.Util.Models;  
  11.     public class SelectGroupController : Controller  
  12.     {  
  13.         //  
  14.         // GET: /Util/SelectGroup/  
  15.         SelectgroupEntities selectgroupEntities = new SelectgroupEntities();  
  16.  
  17.         /// <summary>  
  18.         /// 招生批次  
  19.         /// 李磊 2010-10-29  
  20.         /// </summary>  
  21.         /// <returns></returns>  
  22.         public JsonResult GetAdmissionBatch()  
  23.         {  
  24.             List<SG_Admission_Batchs> admissionBatchsList = selectgroupEntities.admission_batchs.ToList();  
  25.             return Json(admissionBatchsList, JsonRequestBehavior.AllowGet);  
  26.         }  
  27.  
  28.         /// <summary>  
  29.         /// 学历层次  
  30.         /// 李磊 2010-10-29  
  31.         /// </summary>  
  32.         /// <returns></returns>  
  33.         public JsonResult GetEducationLevel()  
  34.         {  
  35.             List<SG_Education_Levels> educationLevelList = selectgroupEntities.education_levels.ToList();  
  36.             return Json(educationLevelList, JsonRequestBehavior.AllowGet);  
  37.         }  
  38.  
  39.         /// <summary>  
  40.         /// 专业  
  41.         /// 李磊 2010-10-29  
  42.         /// </summary>  
  43.         /// <returns></returns>  
  44.         public JsonResult GetProfessional()  
  45.         {  
  46.             List<SG_Professional> professionalList = selectgroupEntities.professional.ToList();  
  47.             return Json(professionalList, JsonRequestBehavior.AllowGet);  
  48.         }  
  49.  
  50.         /// <summary>  
  51.         /// 学籍批次  
  52.         /// 李磊 2010-10-29  
  53.         /// </summary>  
  54.         /// <returns></returns>  
  55.         public JsonResult GetRollBatch()  
  56.         {  
  57.             List<SG_Roll_Batchs> rollBatchList = selectgroupEntities.roll_batchs.ToList();  
  58.             return Json(rollBatchList, JsonRequestBehavior.AllowGet);  
  59.         }  
  60.  
  61.         /// <summary>  
  62.         /// 专业学历层次联动  
  63.         /// 李磊 2010-10-29  
  64.         /// </summary>  
  65.         /// <param name="id"></param>  
  66.         /// <returns></returns>  
  67.         public JsonResult GetProfessionalByEducationLevel(string id)  
  68.         {  
  69.             try 
  70.             {  
  71.                 List<string> professionalIdList = selectgroupEntities.professional_educationlevel.Where(pe => pe.education_id == id).Select(pe => pe.prefessional_code).ToList();  
  72.                 List<SG_Professional> professionalList = selectgroupEntities.professional.Where(p => professionalIdList.Contains(p.prefessional_code)).ToList();  
  73.                 return Json(professionalList, JsonRequestBehavior.AllowGet);  
  74.             }  
  75.             catch 
  76.             {  
  77.                 return null;  
  78.             }  
  79.         }  
  80.     }  
  81. }  

好的,我们接着编写js.

 首先在js的顶层引入 ///<reference path = "../../../Scripts/jQuery-1.4.1.js"/>这样编写js代码就有智能提示,如下

ASP.NET MVC 中使用用户控件


  1. $(document).ready(function () {  
  2.       
  3.     $.ajaxSetup({  
  4.         cache: false 
  5.     });  
  6.     $.getJSON("/SelectGroup/GetAdmissionBatch/"function (data) {  
  7.         $("#admissionBatch").append("<option value=''>请选择</option>");  
  8.         $.each(data, function (i, item) {  
  9.             $("<option></option>")  
  10.             .val(item["admission_batch_id"])  
  11.             .text(item["name"])  
  12.             .appendTo($("#admissionBatch"));  
  13.         });  
  14.  
  15.     });  
  16.  
  17.     $.getJSON("/SelectGroup/GetEducationLevel/"function (data) {  
  18.         $("#edcuationLevel").append("<option value=''>请选择</option>");  
  19.         $.each(data, function (i, item) {  
  20.             $("<option></option>")  
  21.             .val(item["education_id"])  
  22.             .text(item["name"])  
  23.             .appendTo($("#edcuationLevel"));  
  24.         });  
  25.  
  26.     });  
  27.  
  28.     $.getJSON("/SelectGroup/GetProfessional/"function (data) {  
  29.         $("#professional").append("<option value=''>请选择</option>");  
  30.         $.each(data, function (i, item) {  
  31.             $("<option></option>")  
  32.             .val(item["prefessional_code"])  
  33.             .text(item["name"])  
  34.             .appendTo($("#professional"));  
  35.         });  
  36.  
  37.     });  
  38.  
  39.     $("#edcuationLevel").change(function () {  
  40.         $("#professional").empty();  
  41.         $("#professional").append("<option value='0'>请选择</option>");  
  42.         $.getJSON("/SelectGroup/GetProfessionalByEducationLevel/" + $("#edcuationLevel").val(), function (data) {  
  43.             $.each(data, function (i, item) {  
  44.                 $("<option></option>")  
  45.             .val(item["prefessional_code"])  
  46.             .text(item["name"])  
  47.             .appendTo($("#professional"));  
  48.             });  
  49.  
  50.         });  
  51.     });  
  52.  
  53. }) 

ok,好了,我们看看在页面怎么引用


  1. <%Html.RenderPartial("~/Areas/Util/Views/Shared/SelectGroup.ascx"); %> 

只要你将这段代码放在页面上即可。Html.RenderPartial有很多重载,你也可以给用户控件传递一个需要绑定的对象。说到这里谈谈Html.RenderPartial和Html.Partial的区别。Html.RenderPartial是直接输出至当前HttpContext,而Html.Partial是将视图内容直接生成一个字符串并返回。所以在引用的时候不一样分别为<% Html.RenderPartial("~/Areas/Util/Views/Shared/SelectGroup.ascx"); %>和<%= Html.Partial("~/Areas/Util/Views/Shared/SelectGroup.ascx"); %>。说到这两个不免要说Html.RenderAction,它是通过Controller中的Action来调用用户控件。上面的代码大家可以根据js和控制器代码看到,每个下拉列表的绑定都有自己的控制器返回数据,在页面加载完成的时候去调用自己的控制器获取下拉列表数据。如果我们用Html.RenderAction就没有那么麻烦了,看看控制器代码


  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.  
  7. namespace EducationManage.Areas.Util.Controllers  
  8. {  
  9.     using Utility.Json;  
  10.     using EducationManage.Areas.Util.Models;  
  11.     public class SectionGroupController : Controller  
  12.     {  
  13.         //  
  14.         // GET: /Util/SectionGroup/  
  15.         SelectgroupEntities selectgroupEntities = new SelectgroupEntities();  
  16.         public ActionResult Index()  
  17.         {  
  18.             List<SG_Admission_Batchs> admissionBatchList = selectgroupEntities.admission_batchs.ToList();  
  19.             SelectList admissionBatch = new SelectList(admissionBatchList, "admission_batch_id""name""");  
  20.             ViewData.Add("admissionBatch", admissionBatch);  
  21.  
  22.             List<SG_Education_Levels> educationLevelList = selectgroupEntities.education_levels.ToList();  
  23.             SelectList educationLevel = new SelectList(educationLevelList, "education_id""name""");  
  24.             ViewData.Add("educationLevel", educationLevel);  
  25.  
  26.             List<SG_Professional> professionalList = selectgroupEntities.professional.ToList();  
  27.             SelectList professional = new SelectList(professionalList, "prefessional_code""name""");  
  28.             ViewData.Add("professional", professional);  
  29.             return PartialView("~/Areas/Util/Views/Shared/SectionGroup.ascx");  
  30.         }  
  31.  
  32.     }  
  33. }  

再看看前台


  1. <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 
  2. <script language="javascript" type="text/javascript" src="<%=Url.Content("~/Areas/Util/Scripts/SelectGroup.js") %>/> 
  3. <div> 
  4.     <table> 
  5.         <tr> 
  6.             <td style="text-align: right"> 
  7.                 招生批次 
  8.             </td> 
  9.             <td> 
  10.                 <%:Html.DropDownList("admissionBatch", ViewData["admissionBatch"] as SelectList, "请选择", new { id = "admissionBatch"style = "width: 150px" })%> 
  11.             </td> 
  12.             <td style="text-align: right; width: 80px"> 
  13.                 学历层次 
  14.             </td> 
  15.             <td> 
  16.                 <%:Html.DropDownList("edcuationLevel", ViewData["educationLevel"] as SelectList, "请选择", new { id = "edcuationLevel"style = "width: 150px" })%> 
  17.             </td> 
  18.             <td style="text-align: right; width: 80px"> 
  19.                 专业名称 
  20.             </td> 
  21.             <td> 
  22.                 <%:Html.DropDownList("professional", ViewData["professional"] as SelectList, "请选择", new { id = "professional"style = "width: 150px" })%> 
  23.             </td> 
  24.         </tr> 
  25.     </table> 
  26. </div> 

在这里我们一次性就获取到了所有下拉列表要绑定的数据。我们只需要在前台这样应用即可<%Html.RenderAction("Index", "SectionGroup");%>。好了,在MVC2中使用用户控件就是这么简单。




本文转自 BruceAndLee 51CTO博客,原文链接:http://blog.51cto.com/leelei/412702,如需转载请自行联系原作者


上一篇:LeetCode:149_Max Points on a line | 寻找一条直线上最多点的数量 | Hard


下一篇:分享9个最棒的代码片段资源网站