How to display data of the model using foreach in view (.cshtml) in MVC4 razor application?

Are you looking for the code to bind data from model to view in MVC4 razor application? This article will be helpful for you to learn how to bind model data to view in AVC4 razor using .cshtml.

Passing data from model to view is very simple to use. This code snippet gives you idea how to bind data from model to your view so that it can be displayed on the user screen. Model is .cs file where you define all get and set properties so that whenever you place any controls on view, you can bind it with properties in the model. In this example, foreach loop is used to retrieve data. You can make some of fields as mandatory by putting [Required] at top of such property. Following code is used in view:

@model nameofthemodel
ViewBag.Title = "Put your title here";
<!DOCTYPE html>
<title>Put title you want to display.</title>
@if (Model!=null)
foreach (var t in Model.yourlistname)

If the model is null then it will come out of if condition and won't display anything. Make sure correct values are passed through model to view. You can put debugging points to check whether valid data is passed or not.

ViewBag is a dynamic property which is used here for displaying the title. ViewBag does not require typecasting for complex data type hence you can use it for many different purposes.

For each gives you effective mechanism to iterate collection. You can display many properties using @Html.DisplayName statement inside for each loop.

In controller, you have to write code for filling model and then bind model to view. It is always good practice to check model is null or not before binding so that null exceptions won't be thrown at the runtime.


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: