[转载]Asp.Net MVC2 控件开发实例(1)

[转载]Asp.Net MVC2 控件开发实例(1) – 迈克尔二孬 – 博客园.

想开发一个控件,功能比较简单,实现这样一个多选功能:一个文本框,点击时弹出层,左侧展示绑定数据表的数据,右侧为选择后的结果,有左选和右选,取消、清除功能,如下图:

以HtmlHelper的形式调用:

<%=Html.MultiSelectFor(m => m.CodeMC, m => m.CodeDM, dm_jwrylbb,dm<80,,,500,标题, new { @style = width:400px })%>

选择后点击确定,选择项会用分隔符拼接存入文本框,关键信息(如显示项的ID)会存入隐藏域

其中参数按顺序为:文本框ID,隐藏域ID,数据表名称,绑定的数据表过滤条件,分隔符,弹出层高度,标题,htmlAttributes。

思 路:在htmlhelper中构建文本框和隐藏域控件,文本框控件赋予onfocus事件,此事件post调用 PartialViewResult:ShowView(…),此action绑定弹出层所需model,并返回控件view并填充到弹出层中。先来 看helper:(篇幅关系不列出所有重载)

public static MvcHtmlString MultiSelectFor(this HtmlHelper helper, Expression&gt; expressionMC, Expression&gt; expressionDM,string tableName,string condition,string split,int height,string caption, object mcHtmlAttributes)
{
StringBuilder sb = new StringBuilder();
string mcString = ExpressionHelper.GetExpressionText(expressionMC);
string dmString = ExpressionHelper.GetExpressionText(expressionDM);

TagBuilder tag = new TagBuilder("input");
tag.Attributes.Add("type", "text");
tag.Attributes.Add("name", mcString);
tag.GenerateId(mcString);

object mcValue = ModelMetadata.FromLambdaExpression(expressionMC, helper.ViewData).Model;
string mcValueParameter = Convert.ToString(mcValue, System.Globalization.CultureInfo.CurrentCulture);
tag.MergeAttribute("value", mcValueParameter);

TagBuilder tagHidden = new TagBuilder("input");
tagHidden.Attributes.Add("type", "hidden");
tagHidden.Attributes.Add("name", dmString);
tagHidden.GenerateId(dmString);

object dmValue = ModelMetadata.FromLambdaExpression(expressionDM, helper.ViewData).Model;
string dmValueParameter = Convert.ToString(dmValue, System.Globalization.CultureInfo.CurrentCulture);
tagHidden.MergeAttribute("value", dmValueParameter);
RouteValueDictionary dictionary = new RouteValueDictionary();

if (mcHtmlAttributes != null)
tag.MergeAttributes(new RouteValueDictionary(mcHtmlAttributes));
if (!mcHtmlAttributes.ToString().Contains("readonly"))
{
dictionary.Add("onfocus", GetClickEventString(mcString, dmString, tableName, condition, split, height, caption));
}
tag.MergeAttributes(dictionary);
sb.Append(tag.ToString(TagRenderMode.SelfClosing));
sb.Append(tagHidden.ToString(TagRenderMode.SelfClosing));
sb.Append(GetScript(mcString, dmString,height));
return MvcHtmlString.Create(sb.ToString());}

文本框点击事件:(这段折叠显示不出来)

private static string GetClickEventString(string mcName, string dmName, string tableName, string condition, string split,int height,string caption)
        {
            StringBuilder sbClick = new StringBuilder();
            //sbClick.Append("setMSFloat();");
            sbClick.Append("var selectorMC='#'+'" + mcName + "';if($(selectorMC).attr('readonly')==true){return;}");
            sbClick.Append("$.post('/FM/MultiSelect/ShowView',{");
            sbClick.Append("mc:\"" + mcName + "\",dm:\"" + dmName
                + "\",table:\"" + tableName + "\",condition:\"" + condition + "\",sign:\""
                + split + "\",height:\"" + height + "\",mcContent:$('#" + mcName + "').val(),dmContent:$('#" + dmName + "').val()");
            sbClick.Append("},function(data){");
            sbClick.Append("$('#divMS').html(data);}");
            sbClick.Append(");");
            sbClick.Append("$('#divMS').dialog('open');");
            sbClick.Append("$('#divMS').dialog({ title: '" + (string.IsNullOrEmpty(caption) ? "多选" : caption) + "' });");
            return sbClick.ToString();

        } 

其他需要加载的脚本(主要为弹出层初始化代码,弹出层使用了JQuery.ui.dialog,具体使用可查官方文档:http://docs.JQuery.com/UI/Dialog)

private static string GetScript(string modelMCName, string modelDMName,int height)
        {
            StringBuilder script = new StringBuilder();
            script.Append("<script type='text/javascript'>");
            script.Append("$(function () {");

            //script.Append("function setMSFloat(){");
            script.Append("$('<form id=formMS name=formMS><div id=divMS></div></form>').appendTo('body');");
            script.AppendFormat("initDialog('#formMS', '多选', '#divMS', {0}, 480);var s=document.getElementsByName('formMS')[1];$(s).remove();", height);
            //script.Append("};");
            script.Append("});");

            script.Append("</script>");
            return script.ToString();
        }
}

之后是post调用的action:

#region MultiSelectController
public class MultiSelectController : Controller
{
[HttpPost()]
public PartialViewResult ShowView(string mc, string dm, string table, string condition, string sign, int height, string mcContent,string dmContent)
{
string SQL = string.Format(“select * from {0} where 0=0 {1}”, table, string.IsNullOrEmpty(condition) ? string.Empty : “and ” + condition);
System.Data.DataTable dt = ForeignerManagement.Operation.Common.Operation_Common.FillDataTable(SQL);

List msDisplay = new List();

string[] mcArr = mcContent.Split(sign.ToCharArray());
string[] dmArr = dmContent.Split(sign.ToCharArray());
if ((!string.IsNullOrEmpty(mcContent)) && (mcArr.Length == dmArr.Length))
{
for (int i = 0; i < mcArr.Length; i++) { msDisplay.Add(new MSDisplay { MSMC = mcArr[i], MSDM = dmArr[i] }); } } dynamic m = new System.Dynamic.ExpandoObject(); m.CodeCollection = dt.Rows; m.MC = mc; m.DM = dm; m.Sign = sign; m.Height = height - 100; m.ImgHeight = height / 4; m.List = msDisplay; return PartialView("~/Views/Shared/MultiSelect.ascx", m); } } [/csharp] 注:此处使用了动态类型dynamic m = new System.Dynamic.ExpandoObject();省得还得构建一个Model 页面的html和css: [html] <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl” %>

    <% if (Model.CodeCollection != null) { string hrefID = string.Empty; string hrefIDSelector = string.Empty; foreach (System.Data.DataRow dr in Model.CodeCollection as System.Data.DataRowCollection) { hrefID = "l_" + dr["DM"].ToString(); hrefIDSelector = "#" + hrefID; %>

  • ” style=”color:Black;”><%=dr["MC"].ToString()%>
    ” />
  • <% } } %>

” onclick=”rSelect();” />

” onclick=”lSelect();” />
    <% if (Model.List.Count > 0)
    {
    string hID = string.Empty;
    string hSelector = string.Empty;
    foreach (MSDisplay item in Model.List as List)
    {
    hID = “r_” + item.MSDM;
    hSelector = “#” + hID;
    %>

  • ” style=”color:Black”><%=item.MSMC%>


<%=Html.Hidden("hidMC",Model.MC as string) %>
<%=Html.Hidden("hidDM",Model.DM as string) %>

<%=Html.Hidden("sign", Model.Sign as string)%>
[/html]
至此页面已经可以出来了,下面是控件里面的功能事件脚本:

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏