Online: 17166
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.
Views: 70398 | Post Order: 62