ASP中ViewResult()和ActionResult()的区别是什么?净MVC吗?
public ViewResult Index()
{
return View();
}
public ActionResult Index()
{
return View();
}
ASP中ViewResult()和ActionResult()的区别是什么?净MVC吗?
public ViewResult Index()
{
return View();
}
public ActionResult Index()
{
return View();
}
当前回答
ActionResult是一个抽象类。
ViewResult派生自ActionResult。其他派生类包括JsonResult和PartialViewResult。
这样声明它是为了利用多态性并在同一方法中返回不同类型。
e.g:
public ActionResult Foo()
{
if (someCondition)
return View(); // returns ViewResult
else
return Json(); // returns JsonResult
}
其他回答
出于同样的原因,你不需要编写每个类的每个方法来返回"object"。你应该说得尽可能具体。如果您计划编写单元测试,这一点尤其有价值。不再测试返回类型和/或强制转换结果。
ActionResult是一个抽象类,它可以有几个子类型。
ActionResult亚型
ViewResult - Renders a specifed view to the response stream PartialViewResult - Renders a specifed partial view to the response stream EmptyResult - An empty response is returned RedirectResult - Performs an HTTP redirection to a specifed URL RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data JsonResult - Serializes a given ViewData object to JSON format JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client ContentResult - Writes content to the response stream without requiring a view FileContentResult - Returns a file to the client FileStreamResult - Returns a file to the client, which is provided by a Stream FilePathResult - Returns a file to the client
资源
动作方法的ActionResult和ViewResult有什么区别?[ASP。网论坛)
ActionResult是一个抽象类。
ViewResult派生自ActionResult。其他派生类包括JsonResult和PartialViewResult。
这样声明它是为了利用多态性并在同一方法中返回不同类型。
e.g:
public ActionResult Foo()
{
if (someCondition)
return View(); // returns ViewResult
else
return Json(); // returns JsonResult
}
虽然其他答案已经正确地指出了差异,但请注意,如果你实际上只返回ViewResult,最好返回更具体的类型,而不是基本的ActionResult类型。这一原则的一个明显例外是当你的方法返回多个派生自ActionResult的类型时。
关于这一原则背后原因的完整讨论,请参阅这里的相关讨论:必须ASP。NET MVC控制器方法返回ActionResult?
ViewResult是ActionResult的子类。View方法返回一个ViewResult。这两个代码段做的是完全一样的事情。唯一的区别是,对于ActionResult,你的控制器并不承诺返回一个视图——你可以改变方法体,有条件地返回一个RedirectResult或其他东西,而不改变方法定义。