ASP.NET MVC > Output

Return model to view from action method in ASP.NET MVC

How to return a model/object to the view from controller action method?

To return a model from the controller action method to the view, we need to pass the model/object in the View() method.


public ActionResult OutputViewWithModel()
            UserNamePasswordModel model = new UserNamePasswordModel();
            model.UserName = "user";
            model.Password = "Password";
            return View(model); // returns view with model

Here, the View gets the model as UserNamePasswordModel object with its property set. To retrieve properties of this object in the view, we can use @Model; like @Model.UserName or @Model.Password.

View code

Username: @Model.UserName
<br />
Password: @Model.Password 

Instead of a simple class object we can also pass collection of objects to the view like


public ActionResult OutputViewWithModel()
            List<UserNamePasswordModel> list = new List<UserNamePasswordModel>();
            // ... populate list
            return View(list);

Above action method shows OutputViewWithModel view whose model is IEnumerable<UserNamePasswordModel>. To retrieve each item from the Model (in this case IEnumerbale collection), we can use foreach loop.

View code

@foreach (var item in Model)
<p> @item.UserName </p>

Above code will list all UserName from the list on the page.

 Views: 65505 | Post Order: 62

Write for us

Hosting Recommendations