創建一個自定義action必須滿足的要求
方法必須為公共的.
方法不能為靜態方法.
方法不能是 Control基類中的方法(如:ToString,GetHashCode等)
方法不能為擴展方法.
方法不能為一個構 造函數 ,getter, setter.
方法不能包含ref 或 out 參數.
使用 NonActionAttribute 特 性將阻止該action被調用
namespace MVCViewAndAction.Web.Controllers
{
[HandleError]
public class UserDemoController : Controller
{
//
// GET: /UserDemo/
//自定義一個簡單的方法
[NonAction]
//public sealed class NonActionAttribute表示一個特性,該特性用於指示控制器方法不是操作方
法。
public string DisplayString()
{
return "this is a demo string!";
}
}
}
理解Views
相對於 ASP.NET 與 Active Server Pages, ASP.NET MVC 並不包含任何直接對 應的一個頁面。在ASP.NET MVC 應用程序中,你鍵入浏覽器地址欄中的URL在磁盤上並沒有相應的一個頁面, 該URL被映射為 controller actions。與頁面page最相近的正是我們所說的View。
最基本的如下:
public ActionResult Index()
{
return View();
}
為了探究view的本質,以顯示如下的結果:
Code highlighting produced by Actipro
CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> public class UserDemoController : Controller
{
public RssActionResult RssShow()
{
return new RssActionResult();
}
}
我們需要創建一個繼承ActionResult的RssActionResult類,如下所示:
Code
highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->namespace MVCViewAndAction.Common
{
/*
* System.Web.Mvc
public abstract class ActionResult
{
protected ActionResult();
public abstract void ExecuteResult(ControllerContext context);
}*/
public class RssActionResult:ActionResult
{
public RssActionResult()
{
}
//
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("ControllerContext is null!");
}
HttpResponseBase response = context.HttpContext.Response;
Rss rss = new Rss();
rss.CreateSampleRss(response);
}
}