讲讲怎么在 ASP.NET MVC2中使用用户控件。首先我们新建一个用户控件,
 
我们命名为SelectGroup.ascx,代码如下
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 
<script language="javascript" type="text/javascript" src="<%=Url.Content("~/Areas/Util/Scripts/SelectGroup.js") %>"></script> 
<div> 
    <table> 
        <tr> 
            <td style="text-align:right"> 
                招生批次  
            </td> 
            <td> 
                <select id="admissionBatch" style="width: 150px"> 
                </select> 
            </td> 
            <td style="text-align:right; width:80px"> 
                学历层次  
            </td> 
            <td> 
                <select id="edcuationLevel" style="width: 150px"> 
                </select> 
            </td> 
            <td style="text-align:right; width:80px"> 
                专业名称  
            </td> 
            <td> 
                <select id="professional" style="width: 150px"> 
                </select> 
            </td> 
        </tr> 
    </table> 
</div> 
我们再编写其对应的控制器如下
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
 
namespace EducationManage.Areas.Util.Controllers  
{  
    using Utility.Json;  
    using EducationManage.Areas.Util.Models;  
    public class SelectGroupController : Controller  
    {  
        //  
        // GET: /Util/SelectGroup/  
        SelectgroupEntities selectgroupEntities = new SelectgroupEntities();  
 
        /// <summary>  
        /// 招生批次  
        /// 李磊 2010-10-29  
        /// </summary>  
        /// <returns></returns>  
        public JsonResult GetAdmissionBatch()  
        {  
            List<SG_Admission_Batchs> admissionBatchsList =selectgroupEntities.admission_batchs.ToList();  
            return Json(admissionBatchsList, JsonRequestBehavior.AllowGet);  
        }  
 
        /// <summary>  
        /// 学历层次  
        /// 李磊 2010-10-29  
        /// </summary>  
        /// <returns></returns>  
        public JsonResult GetEducationLevel()  
        {  
            List<SG_Education_Levels> educationLevelList = selectgroupEntities.education_levels.ToList();  
            return Json(educationLevelList, JsonRequestBehavior.AllowGet);  
        }  
 
        /// <summary>  
        /// 专业  
        /// 李磊 2010-10-29  
        /// </summary>  
        /// <returns></returns>  
        public JsonResult GetProfessional()  
        {  
            List<SG_Professional> professionalList = selectgroupEntities.professional.ToList();  
            return Json(professionalList, JsonRequestBehavior.AllowGet);  
        }  
 
        /// <summary>  
        /// 学籍批次  
        /// 李磊 2010-10-29  
        /// </summary>  
        /// <returns></returns>  
        public JsonResult GetRollBatch()  
        {  
            List<SG_Roll_Batchs> rollBatchList = selectgroupEntities.roll_batchs.ToList();  
            return Json(rollBatchList, JsonRequestBehavior.AllowGet);  
        }  
 
        /// <summary>  
        /// 专业学历层次联动  
        /// 李磊 2010-10-29  
        /// </summary>  
        /// <param name="id"></param>  
        /// <returns></returns>  
        public JsonResult GetProfessionalByEducationLevel(string id)  
        {  
            try 
            {  
                List<string> professionalIdList = selectgroupEntities.professional_educationlevel.Where(pe => pe.education_id == id).Select(pe => pe.prefessional_code).ToList();  
                List<SG_Professional> professionalList = selectgroupEntities.professional.Where(p => professionalIdList.Contains(p.prefessional_code)).ToList();  
                return Json(professionalList, JsonRequestBehavior.AllowGet);  
            }  
            catch 
            {  
                return null;  
            }  
        }  
    }  
}  
好的,我们接着编写js.
 首先在js的顶层引入 ///<reference path = "../../../Scripts/jQuery-1.4.1.js"/>这样编写js代码就有智能提示,如下
 
$(document).ready(function () {  
      
    $.ajaxSetup({  
        cache: false 
    });  
    $.getJSON("/SelectGroup/GetAdmissionBatch/", function (data) {  
        $("#admissionBatch").append("<option value=''>请选择</option>");  
        $.each(data, function (i, item) {  
            $("<option></option>")  
            .val(item["admission_batch_id"])  
            .text(item["name"])  
            .appendTo($("#admissionBatch"));  
        });  
 
    });  
 
    $.getJSON("/SelectGroup/GetEducationLevel/", function (data) {  
        $("#edcuationLevel").append("<option value=''>请选择</option>");  
        $.each(data, function (i, item) {  
            $("<option></option>")  
            .val(item["education_id"])  
            .text(item["name"])  
            .appendTo($("#edcuationLevel"));  
        });  
 
    });  
 
    $.getJSON("/SelectGroup/GetProfessional/", function (data) {  
        $("#professional").append("<option value=''>请选择</option>");  
        $.each(data, function (i, item) {  
            $("<option></option>")  
            .val(item["prefessional_code"])  
            .text(item["name"])  
            .appendTo($("#professional"));  
        });  
 
    });  
 
    $("#edcuationLevel").change(function () {  
        $("#professional").empty();  
        $("#professional").append("<option value='0'>请选择</option>");  
        $.getJSON("/SelectGroup/GetProfessionalByEducationLevel/" + $("#edcuationLevel").val(), function (data) {  
            $.each(data, function (i, item) {  
                $("<option></option>")  
            .val(item["prefessional_code"])  
            .text(item["name"])  
            .appendTo($("#professional"));  
            });  
 
        });  
    });  
 
}) 
ok,好了,我们看看在页面怎么引用
<%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就没有那么麻烦了,看看控制器代码
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.Mvc;  
 
namespace EducationManage.Areas.Util.Controllers  
{  
    using Utility.Json;  
    using EducationManage.Areas.Util.Models;  
    public class SectionGroupController : Controller  
    {  
        //  
        // GET: /Util/SectionGroup/  
        SelectgroupEntities selectgroupEntities = new SelectgroupEntities();  
        public ActionResult Index()  
        {  
            List<SG_Admission_Batchs> admissionBatchList = selectgroupEntities.admission_batchs.ToList();  
            SelectList admissionBatch = new SelectList(admissionBatchList, "admission_batch_id", "name", "");  
            ViewData.Add("admissionBatch", admissionBatch);  
 
            List<SG_Education_Levels> educationLevelList = selectgroupEntities.education_levels.ToList();  
            SelectList educationLevel = new SelectList(educationLevelList, "education_id", "name", "");  
            ViewData.Add("educationLevel", educationLevel);  
 
            List<SG_Professional> professionalList = selectgroupEntities.professional.ToList();  
            SelectList professional = new SelectList(professionalList, "prefessional_code", "name", "");  
            ViewData.Add("professional", professional);  
            return PartialView("~/Areas/Util/Views/Shared/SectionGroup.ascx");  
        }  
 
    }  
}  
再看看前台
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %> 
<script language="javascript" type="text/javascript" src="<%=Url.Content("~/Areas/Util/Scripts/SelectGroup.js") %>" /> 
<div> 
    <table> 
        <tr> 
            <td style="text-align: right"> 
                招生批次 
            </td> 
            <td> 
                <%:Html.DropDownList("admissionBatch", ViewData["admissionBatch"] as SelectList, "请选择", new { id = "admissionBatch", style = "width: 150px" })%> 
            </td> 
            <td style="text-align: right; width: 80px"> 
                学历层次 
            </td> 
            <td> 
                <%:Html.DropDownList("edcuationLevel", ViewData["educationLevel"] as SelectList, "请选择", new { id = "edcuationLevel", style = "width: 150px" })%> 
            </td> 
            <td style="text-align: right; width: 80px"> 
                专业名称 
            </td> 
            <td> 
                <%:Html.DropDownList("professional", ViewData["professional"] as SelectList, "请选择", new { id = "professional", style = "width: 150px" })%> 
            </td> 
        </tr> 
    </table> 
</div> 
在这里我们一次性就获取到了所有下拉列表要绑定的数据。我们只需要在前台这样应用即可<%Html.RenderAction("Index", "SectionGroup");%>。好了,在MVC2中使用用户控件就是这么简单。
本文出自 “微软技术” 博客,请务必保留此出处http://leelei.blog.51cto.com/856755/412702

ASP.NET MVC 中使用用户控件——转的更多相关文章

  1. ASP.NET MVC加载用户控件后并获取其内控件值或赋值

    有网友看了这篇<ASP.NET MVC加载ASCX之后,并为之赋值>http://www.cnblogs.com/insus/p/3643254.html 之后,问及Insus.NET,不 ...

  2. 在Asp.Net MVC中使用Repeater控件

    使用Repeater控件在视图中展示图表信息,Repeater控件的使用概述: <asp:Repeater ID="Repeater1" runat="server ...

  3. Asp.net 恢复页面内用户控件内的控件ClientID

    众所周知在Asp.net中如果一个页面添加了一个用户控件(或母版页),那么用户控件内的控件的   ClientID号会被自动添加页面中用户控件的ClientID 即页面中的控件内的控件ClientID ...

  4. 在VisualStudio 工具箱中隐藏用户控件

    当我们创建一个用户控件后,VisualStudio会自动将其添加到工具箱中,本来这是一个比较贴心的设计.但是,有的时候,我们并不想将用户控件放到工具箱中. 例如:在WPF中,为了避免一个页面的控件过多 ...

  5. 如何在Web.config中注册用户控件和自定义控件

    问题: 在ASP.NET 的早先版本里,开发人员通过在页面的顶部添加 指令来引入和使用自定义服务器控件和用户控件时,象这样: <%@ Register TagPrefix="scott ...

  6. C# WinForm中添加用户控件

    转:https://blog.csdn.net/haelang/article/details/40681003 有的时候我们需要频繁使用一些系统默认工具的组合,那么就可以使用自定义用户控件. 起一个 ...

  7. C# winform中自定义用户控件 然后在页面中调用用户控件的事件

    下面是用户控件的代码: using System; using System.Collections.Generic; using System.ComponentModel; using Syste ...

  8. C#中,用户控件UserControl里面用Panl加载UserControl,并实现利用委托互相传值

    用户控件主窗体结构:左侧树形菜单,右侧Panl: 根据点击的菜单节点,panl里面选择性加载某一个子窗体用户控件,并传值给子窗体: 反之,在子窗体进行相应的操作之后,传值给主窗体,触发主窗体的刷新. ...

  9. ASP.NET动态加载用户控件的方法

    方法是使用LoadControl方法,根据用户控件的相对路径,动态生成用户控件对象 用户控件 public class UserControlA :UserControl { public UserC ...

随机推荐

  1. Spark高级数据分析· 6LSA

    潜在语义分析 wget http://dumps.wikimedia.org/enwiki/latest/enwiki-latest-pages-articles-multistream.xml.bz ...

  2. fastdfs安装与配置

    FastDFS是一个开源的轻量级分布式文件系统,它对文件进行管理,功能包括:文件存储.文件同步.文件访问(文件上传.文件下载)等,解决了大容量存储和负载均衡的问题.特别适合以文件为载体的在线服务,如相 ...

  3. MR案例:小文件合并SequeceFile

    SequeceFile是Hadoop API提供的一种二进制文件支持.这种二进制文件直接将<key, value>对序列化到文件中.可以使用这种文件对小文件合并,即将文件名作为key,文件 ...

  4. [ARC061E]すぬけ君の地下鉄旅行 / Snuke's Subway Trip

    题目大意:Snuke的城镇有地铁行驶,地铁线路图包括$N$个站点和$M$个地铁线.站点被从$1$到$N$的整数所标记,每条线路被一个公司所拥有,并且每个公司用彼此不同的整数来表示. 第$i$条线路($ ...

  5. POJ-2418 Hardwood Species(二叉搜索树)

    思路就是先将每个单词存进二叉树中,没出现一次,修改该单词所在结点的cnt++: 最后通过递归中序遍历输出结果. 思路很清晰,主要注意一下指针的使用,想一想为什么要这么用? 简单的解释就是,insert ...

  6. jsp中获取list长度

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ tag ...

  7. Spring Boot CRUD+分页(基于Mybatis注解方式)

    步骤一:关于Mybatis Mybatis 是用来进行数据库操作的框架.其中分页使用Mybatis中的PageHelper插件. Mybatis与hibernate对比: 1.hibernate是一个 ...

  8. 整数分解为若干项之和 - PAT

    深度搜索,一开始没有想到,说明基本功还是不够啊,加油 //======================================================================= ...

  9. JavaScript高级程序设计-读书笔记(5)

    第13章 事件 1.事件流 事件流描述的是从页面中接收事件的顺序.IE的事件流是事件冒泡流,而Netscape Communicator的事件流是事件捕获流. (1)事件冒泡,即事件开始时由最具体的元 ...

  10. quartz动态job工具类 serviceh注入问题

    package com.heyi.yanglao.common.job.util; import cn.hutool.core.date.DateUtil; import lombok.extern. ...