ASP.NET Core MVC action result returns different types of content it can be HTML, JSON, string, or empty content. We will explore ViewResult, PartialViewResult, JsonResult, ContentResult, EmptyResult.
Each action result has a different way to return content to the browser. Action result returns result in particular formatting result. For example, JsonResult will return JSON formatted string to the client, ContentResult returns string data that can be formatted in HTML, plain text, or XML. For a more detailed description of the Action Result please visit - ASP.NET Core Action Method and Action Result
The ViewResult returns HTML as a response to the client using the view engine. There are many types of view engines you can use with ASP.NET core, mostly the razor view engine is being used. You can also create a custom view engine.
The ViewResult returns a view with or without any data. Data can be passed using model binding. The View is actually a physical file with extension .cshtml or .vbhtml stored on the file system.
When you just use return View(); MVC finds a view file name as the same name as executing the Action method. For example, an action method with the name Index is being executed then view with name Index.cshtml will be found in the following location of a specific area or root of the application. If the Index.cshtml file does not exist in this location then InvalidOperationException: The view 'Index' was not found is thrown.
ViewResult is inherited from ActionResult class. The view can be returned in multiple ways depending on your requirement. The following controller sets a value of the ViewBag dynamic property and displays it as HTML on view.
public IActionResult Index() { ViewBag.EmployeeID = "1"; ViewBag.FirstName = "Paul"; ViewBag.LastName = "Andrew"; return View(); }
HTML in View
<div> <dl class="row"> <dt class="col-sm-2"> @Html.Label("EmployeeID") </dt> <dd class="col-sm-10"> @ViewBag.EmployeeID </dd> <dt class="col-sm-2"> @Html.Label("FirstName") </dt> <dd class="col-sm-10"> @ViewBag.FirstName </dd> <dt class="col-sm-2"> @Html.Label("LastName") </dt> <dd class="col-sm-10"> @ViewBag.LastName </dd> </dl> </div>
ViewBag should not be used for complex types. You can use ViewBag for properties that are not included in the Model.
You can create strongly type models or view models and bind with views. The model can be a simple or complex type. In complex types, different models will be used for example in the Orders model you can also have a list of OrderDetails models. For more details follow ASP.NET Core Model binding.
The following code uses the Employee model and returns this model with values to View. Notice that the model is explicitly passed to view.
public IActionResult Index() { EmployeeModel employee = new EmployeeModel() { EmployeeID = 1, FirstName = "Paul", LastName = "Andrew", Location = "Mumbai", Email = "Paul@geeksarray.com" }; return View(employee); }
View using Employee Model
@{ ViewData["Title"] = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } @model MVC5Tutorial.Areas.GeeksEmployee.Models.EmployeeModel <div> <dl class="row"> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.EmployeeID) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.EmployeeID) </dd> <dt class="col-sm-2"> @Html.DisplayNameFor(model => model.FirstName) </dt> <dd class="col-sm-10"> @Html.DisplayFor(model => model.FirstName) </dd> --other properties of model </dl> </div>
As mentioned earlier MVC will look for a View file in a specific location however you can explicitly mention a different View file to render. This is very useful to render the view conditionally.
You can use return View("~/Areas/[Area Name]/[Controller Name]/Views/[View Name].cshtml"). Following code returns a view from different than current executing area.
return View("~/Areas/Employee/Views/Employee/Index.cshtml");
If you want to pass a model then you can use the following code.
public IActionResult Index() { EmployeeModel employee = new EmployeeModel() { EmployeeID = 1, FirstName = "Paul", LastName = "Andrew", Location = "Mumbai", Email = "Paul@geeksarray.com" }; return View("~/Areas/Employee/Views/Employee/Index.cshtml" ,employee); }
If Area is not required and wants to return a view from the root folder then you can use the following code.
return View("~/Views/Employee/Index.cshtml" ,employee);
The PartialViewResult is like injecting reusable HTML to the main view. Partial views are also a physical file with extension .cshtml or .vbhtml from file system. In the real-time application menu, footer, login are some of the examples where its HTML will be injected to many other main views.
You can create a partial view as you create a normal view and render it through the main view as in the following code. You can also pass the current model or sub-model of current to the partial view.
In the following code _address is the name of partial view located in the same controller's view folder. EmployeeAddress is a model used by the main address and passed to partial view.
<div> @{ @await Html.PartialAsync("_address", Model.EmployeeAddress);} </div>
There are many different ways to render a partial view from HTML of the main view, controller, or jquery. You can see details of each method here how to render partial view in asp.net mvc
This action method formats object to JSON. You can return a JSON string or serialize/deserialize the model object.
Prior to ASP.NET Core 3.0 Newtonsoft.Json was used for serialization and deserialization. ASP.NET Core 3.0 introduced System.Text.Json which is faster and built-in with .NET Core. Here is the benchmark between Newtonsoft.Json and System.Text.Json.
The following code serializes a Model object to JSON string and returns this string to the client. The client can be anything the browser or jQuery AJAX request from view.
public JsonResult Index() { EmployeeModel employee = new EmployeeModel() { EmployeeID = 1, FirstName = "Paul", LastName = "Andrew", Location = "Mumbai", Email = "Paul@geeksarray.com" }; return Json(employee); }
If you are executing this from browser you will see output like this.
JSONResult mostly used by ASP.NET Web API or the jQuery AJAX call. You can use the following code to execute the action method to get JSON object by jQuery AJAX request on button click.
<div> <button type="button" id="btnGetEmployee" class="btn btn-info pull-right">Get Employee Details</button> </div> <div> <table id="tblEmployee"> <tbody></tbody> </table> </div> <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#btnGetEmployee").click(function () { $("#tblEmployee tbody tr").remove(); $.ajax({ type: 'POST', url: 'https://localhost:44371/Employee/index/1', dataType: 'json', success: function (data) { var items = ''; $.each(data, function (i, item) { var rows = ''; rows = "<tr><td>" + item + "</td></tr>" $('#tblEmployee tbody').append(rows); }); }, error: function (xhr, textStatus, error) { alert(error); }, failure: function (response) { alert("failure " + response.responseText); } }); return false; }) }); </script>
The ContentResult writes response as a string literal. You can return raw HTML or JSON or plain string to the browser using ContentResult.
The Content() method accepts three parameters.
The following code returns html content with bold and italic text.
public ContentResult Index() { string content = "<div><b><i>Hello from GeeksArray team, this is example of content action method.</b></i></div>"; return Content(content, "text/html"); }
This generates output as following image.
To return ContentResult with HTTPStatusCode you can use the StatusCode property as shown in the following code.
public ContentResult Index() { string content = "Hello from GeeksArray team, this is example of content action method."; ContentResult result = new ContentResult(); result.Content = content; result.ContentType = "text/plain"; result.StatusCode = (int)HttpStatusCode.OK; return result; }
The EmptyResult does not return anything to client side. It is just like a void method.
It is useful when you just want to execute some logic but do not want to return anything to the client. For example, recording the client location.
public EmptyResult EmptyData() { //code to execute some logic return new EmptyResult(); }