软件下载 | 资讯教程 | 最近更新 | 下载排行 | 一键转帖 | 发布投稿
您的位置:最火下载站 > 网络编程 > ASP.NET > ASP.NET MVC 1.0 - 10. Controller

ASP.NET MVC 1.0 - 10. Controller

烈火网(liehuo.net)提示:点击新窗口预览!

1. View

最常用的一种,用于返回一个 "标准" 页面。

protected internal virtual ViewResult View(string viewName, string masterName, object model)
{
if (model != null)
{
base.ViewData.Model = model;
}

return new ViewResult
{
ViewName = viewName,
MasterName = masterName,
ViewData = base.ViewData,
TempData = base.TempData
};
}

public class ViewResult : ViewResultBase
{
protected override ViewEngineResult FindView(ControllerContext context)
{
ViewEngineResult result = ViewEngineCollection.FindView(context, ViewName, MasterName);

if (result.View != null)
{
return result;
}

...
}
}

这个页面默认是 ViewPage,也可以是我们自己定义的其它模板引擎页面。

MVC 还提供了强类型的 ViewPage<TModel>。

public class User
{
public string Name { get; set; }
public int Age { get; set; }
}

public class TestController : Controller
{
public ActionResult Index()
{
ViewData["message"] = "Hello, World!";
var model = new User { Name = "Tom", Age = 13 };

return View(model);
}
}

Index.aspx
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<Learn.MVC.Controllers.User>" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Index</title>
</head>
<body>
Name: <%= Model.Name %>; Age: <%= Model.Age %>
</body>
</html>

在 WebForm 时代,我们就已经习惯了将一个页面分解成多个 UserControl,现在我们依然可以这么做。htmlHelper 专门提供了 RenderPartial 扩展方法,从当前视图目录(Views\xxx)下载入 .ascx 页面。

public static class RenderPartialExtensions
{
public static void RenderPartial(this HtmlHelper htmlHelper, partialViewName, model, viewData)
{
htmlHelper.RenderPartialInternal(partialViewName, viewData, model, ViewEngines.Engines);
}
}

public class HtmlHelper
{
internal virtual void RenderPartialInternal(string partialViewName, ViewDataDictionary viewData,
object model, ViewEngineCollection viewEngineCollection)
{
...

ViewDataDictionary newViewData = null;

if (model == null)
{
if (viewData == null)
newViewData = new ViewDataDictionary(ViewData);
else
newViewData = new ViewDataDictionary(viewData);
}
else
{
if (viewData == null)
newViewData = new ViewDataDictionary(model);
else
newViewData = new ViewDataDictionary(viewData) { Model = model };
}

ViewContext newViewContext = new ViewContext(ViewContext, ViewContext.View,
newViewData, ViewContext.TempData);

IView view = FindPartialView(newViewContext, partialViewName, viewEngineCollection);

view.Render(newViewContext, ViewContext.HttpContext.Response.Output);
}

internal static IView FindPartialView(viewContext, partialViewName, viewEngineCollection)
{
ViewEngineResult result = viewEngineCollection.FindPartialView(viewContext, partialViewName);

if (result.View != null)
{
return result.View;
}

...
}
}

相关阅读
栏目导航
推荐软件