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.
ACTION METHOD CODE
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
CONTROLLER CODE
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.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...