CodeDigest.Com Logo
Featured:

Multiple Ways to Pass Data from Controller Action Method to View in Asp.Net MVC

Tagged as: Asp.Net MVC Asp.Net Core MVC Posted By

It is a very common requirement in every Asp.Net MVC application where we need to pass data from the controller action method to view to render the HTML output. This simple article will help you understand various methods available in Asp.Net MVC to pass data from action method to razor view.

Using ViewData

ViewData is dictionary object of type System.Web.Mvc.ViewDataDictionary which takes data as key value pair. The data can be set in Action method and it will be accessible in View. The data in ViewData can be used to display or modified in the View page and it will be available again in the action method when the view is posted back.

The below action method sets a string message to display in the view page.

 

public ActionResult Index()
{
      ViewData["Message"] = "Data from Action Method!";
      return View();
}

 

To display in view page,

 

@ViewData["Message"]

 

We can also pass objects from action methods. The below code uses ViewData to pass the list items to bind DropDownList control.

Action

public ActionResult edit(int id)
{

      Employee emp = db.Employees.Where(e => e.EmployeeId == id).FirstOrDefault();
      ViewData["DepartmentListItems"] = db.Departments.Distinct().Select(i => new SelectListItem() { Text = i.DepartmentName, Value = i.DepartmentId.ToString() }).ToList();
      return View(emp);

}

 

View

 

@Html.DropDownListFor(model => model.DepartmentId, ViewData["DepartmentListItems"] as IEnumerable<SelectListItem>,"Select")

 

Using ViewBag

ViewBag is dynamic object which helps to pass values from controller action method to view. Using ViewBag, we can dynamically define a property on the ViewBag and assign a value in action method which can be accessed in the View page using the same property name. It is actually wrapper of ViewData object represented as dynamic type released in C# 4.0.

For example, the below code uses ViewBag to pass the list item from the controller action to bind a DropDownList in view page.

Action

 

public ActionResult edit(int id)

{

    Employee emp = db.Employees.Where(e => e.EmployeeId == id).FirstOrDefault();

    if (emp != null)

        ViewBag.DepartmentId = new SelectList(db.Departments.ToList(), "DepartmentId", "DepartmentName", emp.DepartmentId);

    return View(emp);

}

 

View

 

@Html.DropDownList("DepartmentId")

 

Using ViewModels

This is mostly used and recommended approach to pass data from controller action method to view. ViewModels are C# objects that are used to pass the data from action method to a strongly typed view. This is recommended approach because it allows unit testing of controller code easily and it is strongly typed when compared to using ViewData and ViewBag.

The below code uses the SavedArticlesListViewModel to pass list of articles from controller to display in view page.

ViewModel

public class SavedArticlesListViewModel

{

     public UserArticles articles { get; set; }

     public int CurrentPage { get; set; }

     public int PageSize { get; set; }

}

 

Action

public ActionResult SavedArticles(int? page)

{

   int PageSize = int.Parse(ConfigurationManager.AppSettings["UserArticlePageSize"]);

   SavedArticlesListViewModel savedVM = new SavedArticlesListViewModel

   {

         articles = repositoryPost.GetSavedArticles(CurrentUser,page ?? 1,PageSize),

         CurrentPage = page ?? 1,

         PageSize = PageSize

   };

 

   return View(savedVM);

}

 

View

 

@model OrangeWeb.Web.ViewModel.SavedArticlesListViewModel

<ol>

@foreach (OrangeWeb.Domain.Entities.Article art in Model.articles.articles)

{

<li>

@art.Title

</li>

}

<ol>

 

View Injection

View Injection is another new approach released in Asp.Net Core MVC (or previously called Asp.Net MVC 6.0) which allows injecting a dependent service into a view page. Though it is feature to inject a dependent service, you can use this approach to pass data to view from a service class.

Read View Injection,Action Injection and Resolving Framework Services using Asp.Net Core MVC DI Container to know more about View Injection.



Feedback

Comments