控制器
在MVC中每一个浏览器请求都会对应一个相应请求的控制器(Controller),
举个例子,设想一下你在浏览器地址栏输入了下面的URL:
http://localhost/product/index/3
在这种情况下,将会调用一个名为ProductController的控制器。ProductController负责生成对浏览器请求的响应。
我们新建一个控制器
public class Default1Controller : Controller
{
public ActionResult Index()
{
return View();
}
}
一个控制器是一个继承自System.Web.Mvc.Controller基类的类。因为控制器继承自这个基类,所以控制器轻松地继承了一些有用的方法
控制器(Controller)
1,控制器(Controller)的方法必须是公共类型的方法,这样的话用户通过地址栏可以直接访问到该方法,所以安全性要做好
2,控制器(Controller)不能是重载,并且也不能是静态方法
控制器(Controller)返回结果
一般情况控制器返回结果我们都会用到基类中的方法,比如创建时候的 return View();
提供了11种ActionResult的实现
代码实例
using System.Web.Mvc;
namespace MvcApplication1.Controllers
{
public class ActionResultController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ContentResult()
{
return Content("Hi, 我是ContentResult结果");
}
public ActionResult EmptyResult()
{
//空结果当然是空白了!
//至于你信不信, 我反正信了
return new EmptyResult();
}
这样调用只会在页面输出 必须这样调用才行
<script src="@Url.Action("GetTime")" type="text/javascript"></script>
public ActionResult JavaScriptResult()
{
string js = "alert(\"Hi, I'm JavaScript.\");";
return JavaScript(js);
}
//AllowGET允许使用get请求
public ActionResult JsonResult()
{
var jsonObj = new
{
Id = 1,
Name = "小铭",
Sex = "男",
Like = "足球"
};
return Json(jsonObj, JsonRequestBehavior.AllowGet);
}
//地址重定向 直接跳到转相应地址下
public ActionResult RedirectResult()
{
return Redirect("~/demo.jpg");
}
//路由重定向 跳转到指定地址
public ActionResult RedirectToRouteResult()
{
return RedirectToRoute(new {
controller = "Hello", action = ""
});
}
public ActionResult ViewResult()
{
return View();
}
//部分视图
public ActionResult PartialViewResult()
{
return PartialView();
}
//禁止直接访问的ChildAction
[ChildActionOnly]
public ActionResult ChildAction()
{
return PartialView();
}
}
}
更改Action名称
[ActionName("NewActionName")]
public ViewResult pp()
{
return null;
}