您的位置:首页 > 编程语言 > ASP

ASP.NET MVC 重点教程一周年版 第十一回 母版页、用户自定义控件及文件上传

2009-04-29 11:41 691 查看

母版页(Master)

1.母版页是与Controller无关的,母版页只是一个View文件,而没有任何Controller与之相对应。

2.其实在ASP.NET MVC中View的aspx与母版页并不像WebForm中那样紧密关联。

例如我想更换一个aspx的母版页,只要在Action中return 时指定所要使用的Master即可:





如图我有2个Master文件,而/Views/Home/Index.aspx则为





这时我们如果想要使用Site2做为Master,只要在Action中return View指定masterName的参数即可:

[code]
[code] public ActionResult Index() {


return View(null,"Site2");


}

[/code]
[/code]

自定义控件

RenderPartial

ASP.NET MVC中如果要自定义控件的话并不能像WebForm那样用<cc1:xxxx />这样来引用,而要使用Helper。

例如我们建立一个ct.ascx





其内容:

[code]
[code] <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>


我是ct.ascx

[/code]
[/code]
然后在Index.aspx里调用

[code]
[code] <%Html.RenderPartial("ct"); %>

[/code]
[/code]
OK(注意这里不是用<%=%>显示而是执行语句)

最终显示结果就是:





用户自定义控件除了放在调用者同一目录下,也可以放在View/Shared中。而且这种自定义控件也是没有Controller支持的,仅是将View的部分提取为公共使用。

那么如果我们想调用的ascx有逻辑处理或调用数据库,也就是需要Controller的情况下,我们应该怎么办呢。

RenderAction

OK比如我想有一个有独立逻辑的ascx.

先要引用 Microsoft.Web.Mvc(http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471)

web.config/configuration/System.Web/pages/namespaces添加<add namespace="Microsoft.Web.Mvc"/>

那么和建立一个Action是一样的

Action:

[code]
[code] public ActionResult CtAction() {


return PartialView();//注意这里不是View


}

[/code]
[/code]
View(CtAction.ascx)

[code]
[code] <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>




显示当前Action:<%=this.ViewContext.RouteData.Values["action"]%>

[/code]
[/code]
[code] <%


 Html.RenderAction("ctaction","home"); %>

[/code]
[/code]
OK运行起来,结果为:





文件的上传

下面来说一下与本篇本无关的话题就是文件的上传,我这里也不多做解释了,代码就是最好的语言。

View:

[code]
[code] <form action="<%=Url.Action("Process") %>" enctype="multipart/form-data" method="post">


<input name="up1" type="file" /> <input type="submit" />


</form>

[/code]
[/code]
Action(Process):

[code]
[code] public ActionResult Process(HttpPostedFileBase up1)


{//参数名与name名一致即可


 up1.SaveAs(Server.MapPath("~/" + up1.FileName));


 return Content(up1.FileName);


}

[/code]
[/code]

显示:



提交后:



再看看文件夹,文件已经上传成功:





至此,我想ASP.NET MVC重典一周年版已经没有什么基础东西可以讲了,如果大家想进一步学习ASP.NET MVC,请关注Asp.net Mvc Framework 系列的随时更新
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐