Different ways to produce output in ASP.NET MVC using Action Methods

Sheonarayan
Posted by in ASP.NET MVC category on for Intermediate level | Points: 250 | Views : 21369 red flag
Rating: 5 out of 5  
 2 vote(s)

In this article, we are going to learn different ways to produce output to the web page using action methods in ASP.NET MVC.
Recommendation
Read Developing a star rating in ASP.NET MVC before this article.

Introduction


Action methods are the obvious way to produce output to the web page from controller in ASP.NET MVC. Be it a complete web page, a string or an object. This article details almost all action methods available in ASP.NET MVC.

Though there are many overloads of these action methods, below descriptions are of those overloads that are frequently used.

Each action method returns different types of action results however most of action results derives from "ActionResult" class so returning "ActionResult" from these controller method would suffice our need. For the shake of clarity and understanding below controller methods return respective action results.

View Action Method


View() Action method

View() action method is used to render a view as a web page. In this case, View will be the .cshtml page available in the View folder with the name of the method from which this is being called.
public ViewResult OutputView()
        {
            return View();
        }
The above View() method will render OutputView.cshtml (the location of this View depends on under which controller this method is written) from Views folder to the browser. View() method returns ViewResult action type that derives from ActionResult class.

View(Model) action method
View() method when passed with an object as a parameter returns the View as a web page, with the object (model) being passed so that View can use this model to render data.

public ViewResult OutputViewWithModel(UserNamePasswordModel model)
        {
            return View(model); // returns view with model
        }     
The above method will render OutputViewWithModel.cshtml from Views folder to the browser.

The View must have @model directive in order to retrieve data from Model.
@model Restaurant.Models.UserNamePasswordModel

@{
    ViewBag.Title = Model.UserName;
}
View("ViewName") action method
View() method when passed with the View name renders the view that is passed as parameter as a web page.
public ViewResult OutputViewWithModel(UserNamePasswordModel model)
        {
            return View("OutputView"); // returns the view that is passed as paramter
        }
The above code will render "OutputView" view to the page. Please note that View name should not contain the extension name (.cshtml) of the view.

PartialView("_PartialViewName") action method


PartialView() action method when passed partial view name as parameter returns the Partial View as a web page.
public PartialViewResult OutputPartialView()
        {
            return PartialView("_MyPartialView"); 
        }
This method can accept 2nd parameter as model object to return along with the partial view so that this view can use Model to retrieve data. PartialView() method returns PartialViewResult action result that intern derives from ActionResult class.

Redirect("url") action method


Redirect() action method when passed url as parameter redirect user to the url that is passed.
 public RedirectResult OutputRedirectView()
        {
            return Redirect("/controllerandaction/ReceiveWithRequestFormCollection");
        }
The above code will redirect user to "ReceiveWithRequestFormCollection" method of "controllerandaction" controller. Redirect() method returns RedirectResult action result that derives from ActionResult.

RedirectToRoute() action method


RedirectToRoute() action method when passed Route name as parameter redirects the user to that particular route defined in App_Start/RouteConfig.cs. This method returns RedirectToRouteResult action result that intern derive from ActionResult class.
public RedirectToRouteResult OutputToAction()
        {
            // return RedirectToAction("OutputPartialView");
            return RedirectToRoute("MyCustomRoute");
        }
Route config
 routes.MapRoute(
                name: "MyCustomRoute",
                url: "CustomController/{action}/{id}",
                defaults: new { action = "Index", id = UrlParameter.Optional }
            );
The parameters, if any defined in the route gets its default value, if not we need to pass 2nd parameter as route values.
return RedirectToRoute("MyCustomRoute", new { Id = 5 });

Content() action method


Content() method renders the string that is passed as parameter to the browser.
public ContentResult OutputContent()
        {
            return Content("This is content.");
        }

When above controller method is called, it simply render "This is content." in the browser. This method returns ContentResult action result that derives from ActionResult.

Json() action method


Json() method returns Json string to the browser. Its return type is JsonResult that derives from ActionResult.
public JsonResult OutputToJson()
        {
            UserNamePasswordModel model = new UserNamePasswordModel()
            {
                Password = "Password1",
                UserName = "UserName1"
            };
            return Json(model, JsonRequestBehavior.AllowGet);
        }

// OUTPUT: {"UserName":"UserName1","Password":"Password1"}
The above code converts the UserNamePasswordModel to the Json string and returns to the browser.

JavaScript() action method


JavaScript() action method returns JavaScript code to the browser. This method returns JavaScriptResult action result that derives from ActionResult class.
public JavaScriptResult OutputJavaScriptAlert()
        {
            string a = "alert('this is alert')";
            return JavaScript(a);
        }
To test this, create a view with following code
Try clicking on the link below
  
@Ajax.ActionLink("Test JavaScript", "OutputJavaScriptAlert", new AjaxOptions{UpdateTargetId = "divLink"}) 
Now, after running your project try clicking on the link and you will get an alert like below.


File() action method


File() action method returns the content of a file to the browser. The return type of this method is FileResult that again derives from ActionResult.

public FileResult OutputFile()
        {
            string path = Server.MapPath("~/Views/Home/About.cshtml");
            return File(path, "text/html");
        }

Hope this article was helpful, do comment and refer to your friends and colleagues. Thanks for reading and keep visiting for more ASP.NET MVC related articles.

Reference: MSDN

Page copy protected against web site content infringement by Copyscape

About the Author

Sheonarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com
http://www.snarayan.com
Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Udayreddy on: 3/21/2014 | Points: 25
Nice article. Thank you.

Login to post response

Comment using Facebook(Author doesn't get notification)