您的位置:首页 > Web前端 > JQuery

基于ASP.NET MVC的JQueryUI控件开发(1)

2010-07-21 10:33 501 查看
看了一些别人写的ASP.NET MVC控件,决定自己写一个基于JqueryUI的ASP.NET MVC控件集出来,

1.下载JQueryUI 1.8

2.创建MVC工程和类库工程,并将JQueryUI的JS和CSS引入MVC工程,如下图:


001.png (大小:17.9 K 下载次数:0)



3.修改Site.Master文件,引入JQueryUI的相关JS和CSS


002.png (大小:8.7 K 下载次数:0)



4. 编写扩展程序,这里主要用的是扩展方法

在JQuery中有一个很重要的方法就是初始化处理,一般形式为

<script>

$(function(){

//初始化处理

});

</script>

要实现这种自动代码我参照Html.BeginForm的例子

<% using (Html.BeginForm()) { %>

----

<% } %>

在页面中就会有<form> </form>标记。

编写一个HtmlScript类:

namespace Hahaman.Mvc.UI

{

public class HtmlScript: IDisposable

{

private HtmlHelper hh;

private bool init;

public HtmlScript(HtmlHelper hh): this(hh, false)

{

}

public HtmlScript(HtmlHelper hh,bool init)

{

this.hh = hh;

this.init = init;

var html = "<script>";

hh.ViewContext.Writer.WriteLine(html);

if (init)

html = "$(function(){";

hh.ViewContext.Writer.WriteLine(html);

}

#region IDisposable 成员

public void Dispose()

{

if (init)

{

hh.ViewContext.Writer.WriteLine("});");

}

hh.ViewContext.Writer.WriteLine("</script>");

}

#endregion

}

}

构造参数有两个,一个是HtmlHelper,另一个是否要进行初始化。

编写一个扩展类:

namespace Hahaman.Mvc.UI

{

public static class JQueryUIExt

{

public static HtmlScript BeginScript(this HtmlHelper hh,bool init)

{

return new HtmlScript(hh, init);

}

public static void EndScript(this HtmlHelper hh,bool init)

{

if (init)

{

hh.ViewContext.Writer.WriteLine("});");

}

hh.ViewContext.Writer.WriteLine("</script>");

}

}

}

增加两个方法,一个是BeginScript,另一个是EndScript.

使用方法:

页面导入命名空间:

<%@ Import Namespace="Hahaman.Mvc.UI" %>

代码:

<%using (Html.BeginScript(true)) { %>

<%}%>

客户端就会生成:

<script>

$(function(){

});

</script>

也可以:

<%using (Html.BeginScript()) { %>

<%}%>

客户端就会生成:

<script>

</script>

下来就是写扩展方法了:

先写两个试一下:

public static void Draggable(this HtmlHelper hh, string id)

{

hh.ViewContext.Writer.WriteLine( "$(/""+id+"/").draggable();");

}

public static void Draggable(this HtmlHelper hh, string id,string config)

{

hh.ViewContext.Writer.WriteLine("$(/"" + id + "/").draggable({"+config+"});");

}

完成拖拽功能,使用方法:

<div class="div1" style="border:solid 1px;width:200px;height:200px;background-color:green">

haha

</div>

<%using (Html.BeginScript(true))

{ %>

<%Html.Draggable(".div1","opacity: 0.3");%>

<%}%>

这样div1就可以拖拽了!

待续....

代码已发布到http://jqueryuimvc.codeplex.com/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: