Action methods are the obvious way to produce output to the web page from controller in ASP.NET MVC. It can be a complete web page, a string or an object. Start from today until the next few days, we're going to learn different ways to produce output to the web page using action methods in ASP.NET MVC. 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 your need.

In this part, I will show you how to use View Action Methods that are available to produce an output in ASP.NET MVC.

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.

That's the way to produce output in ASP.NET MVC using View Action Method. Just look forward to further discussion in the next article.

HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.