Actions in ASP.NET MVC 3
Introduction
ASP.NET MVC provides a new way of creating web applications which are more extensible and testable. We discussed about ASP.NET MVC in Introduction to ASP.NET MVC 3. Also, we discussed about Routers and Controllers in ASP.NET MVC 3. Here, we will take a deeper look into the different Actions, Action filters, and selectors used inside a Controller.
Action Result
By default, the Controller actions will return the ActionResult
object. We can return various types of results as ActionResult
, which will decide how the output needs to render on the browser.
public ActionResult About()
{
return View();
}
Sample Controller
For our sample, we will use the following SampleController
in addition to the default HomeController
and AccountController
.
public class SampleController : Controller
{
//
// GET: /Sample/
public ActionResult Index()
{
return Content("Hello from Index action in Sample Controller");
}
public ActionResult Verify(string username = "all")
{
return Content("Hello from Verify action in Sample Controller");
}
}
Here, we will discuss about some of the ActionResult
s available as part of ASP.NET MVC 3.
1. Content
When we need to return any text from a Controller action, we will use the Content
type.
public ActionResult Index()
{
return Content("Hello from Home Controller");
}
2. RedirectToAction
Depending on the input values, we can redirect to another Action. For redirecting to another Action, we will use the RedirectToAction
type.
public ActionResult Index()
{
// Redirect to Verify action inside the Sample Controller
return RedirectToAction("Verify", "Sample");
}
3. RedirectToRoute
When we need to redirect to a route defined in Global.asax, we will use the RedirectToRoute
object.
As part of our sample application, we have a custom route defined with the name “sample
”. This will route to the Index action inside the Sample Controller. For more on Custom routes, please refer to Controllers and Routers in ASP.NET MVC 3.
public ActionResult Index()
{
return RedirectToRoute("sample");
}
4. File
File
is used to return the content of a file to the browser. For our sample, I am returning the web.config to the browser.
public ActionResult Index()
{
return File("Web.config", "text/html");
}
5. JSON
We can render the text to the result page or can send it as a file to the client using JSON notation.
public ActionResult Index()
{
return Json("hello from JSON","text/html", JsonRequestBehavior.AllowGet);
}
As we specified the type of the content, it will render to the browser as shown below:
public ActionResult Index()
{
return Json("hello from JSON", JsonRequestBehavior.AllowGet);
}
If there is no content type specified, it will download the content as a file.
Action Filters
There are a set of Action filters available with ASP.NET MVC 3 to filter actions. Action filters are defined as attributes and applied to an Action or controller.
1. Authorize
Authorize filters ensure that the corresponding Action will be called by an authorized user only. If the user is not authorized, he will be redirected to the login page.
[Authorize]
public ActionResult About()
{
return View();
}
If the user is not authorized and invoke the About action, then he will redirected to the log on page.
If we need the filter at the controller level, then we can add the filter to the controller class itself.
[Authorize]
public class SampleController : Controller
{
……………………………………………
}
2. HandleError
HandleError
will handle the various exceptions thrown by the application and display user friendly message to the user. By default, this filter is registered in Global.asax.
Note: If any of the Action filters are added to the filter collection in Global.asax, then the scope of the filter is the application.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
For verifying a filter, let us enable a custom error in web.config:
<customErrors mode="On"/>
Now throw an exception from the Home Controller:
public ActionResult Index()
{
throw new Exception("Verify the HandleError filter");
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
Now run the application and observe the custom error message:
This View is defined under Shared Views. We can change the error message using the Error.cshtml file.
Now, let us remove the filter from Global.asax and verify our application. We will receive the following server error:
Now, let us update the CustomError
tag to RemoteOnly
and verify our application. Now we can see this error message thrown by the application:
We can specify the HandleError
filter for an Action or a controller.
ASP.NET MVC defines Action filters like OutputCache
, ValidateInput
, etc., as part of ASP.NET MVC 3, which we will discuss later.
Action Selectors
ASP.NET MVC 3 defines a set of Action selectors which determine the selection of an Action. One of them is ActionName
, used for defining an alias for an Action. When we define an alias for an Action, the Action will be invoked using only the alias; not with the Action name.
[ActionName("NewAbout")]
public ActionResult About()
{
return Content("Hello from New About");
}
ASP.NET has more Action selectors like HTTPPost
and HTTPGet
, which we will discuss later.
Conclusion
Here we had a quick discussion of the various Action result options and Action filters. We will discuss more about Views, Styles, etc., in the next article.
发表评论
2024年男性、女性に超人気がある新素材入荷
┏┯┓
┠超┨新品腕時計 、バッグ、財布、手帳、
┗┷┛★送料無料(日本全国)★
┏┯┓◆CARTIER ◆OMEGA ◆FENDI◆シャネル
┠人┨◆コーチ ◆ブルガリ◆ROLEX◆HUBLOT
┗┷┛◆FRANCK MULLER ◆ルイ・ヴィトン
┏┯┓ルイヴィトン 財布 値段
┠気┨シャネル 財布 人気
┗┷┛IWC 腕時計
┏┯┓シャネル 時計 新作
┠時┨ジェイコブ 時計
┗┷┛100%品質保証!満足保障!リピーター率100%
┏┯┓信用の第1、良い品質、低い価格。
┠計┨必ずご満足頂ける品質の商品のみ販売しております。
┗┷┛店長は2024最新型腕時計ブランドを推薦しますy9LFMb you ave a great weblog right here! would you wish to make some invite posts on my blog?
LexFo0 Some really interesting information, well written and generally user friendly.
Dm3KUj This blog was how do I say it? Relevant!! Finally I ave found something which helped me. Kudos!
Your style is so unique in comparison to other people I have read stuff from. Thank you for posting when you ave got the opportunity, Guess I all just book mark this site.
9PRLO8 Your style is so unique compared to other folks I ave read stuff from. Many thanks for posting when you ave got the opportunity, Guess I will just bookmark this page.
f1j4XX incredibly nice post, i unquestionably genuinely like this website, retain on it
BIElzD Spot on with this write-up, I really think this amazing site needs much
jF84Mx
nthGHE The style and design look great though! Hope you get the issue fixed soon.
OcFuOj I really enjoy the blog post.Much thanks again. Keep writing.
QBwEmE I really liked your blog post. Really Great.
HfTjPo I loved your blog.Thanks Again. Really Great.
We have gone ahead and added a hyperlink back to your webpage from one of my clients requesting it. I've used your site URL: and blog title: to be sure you get the correct anchor text. If you woud like to check out where your hyperlink has been placed, please e-mail me at:. Appreciate it
Have you ever ever considered including extra movies to your blog posts to keep the readers more entertained? I mean I simply learn by your complete article of yours and it was fairly good but since Im more of a visual learner,I discovered that to be extra useful effectively let me know the way it seems! I love what you guys are always up too. Such clever work and reporting! Sustain the great works guys Ive added you guys to my blogroll. This can be a great article thanks for sharing this informative information.. Ill go to your weblog regularly for some newest post. Anyway, in my language, there are usually not much good source like this.