Search code examples
asp.net-mvcrazor

Accessing ViewModel properties in the view


I have seen a lot of trivial examples of accessing ViewModel properties in the view. What I need is traverse through an array (one of the properties is an array) and display them in the table..

I pass the following ViewModel to my view:

  public class myViewModel
    {

        public List<SomeObject> listofObjects {get;set}

        //other properties....       

    }

    public class SomeObject {
         public string Id {get;set;}
         public string Name {get; set;}
         public string Someotherprop {get; set;}
    }

Question # 1: How do I loop through the listOfObjects and display all their properties in the table? I am using asp.net mvc 3 with Razor.

Question # 2: How do I make this array accessible in my JavaScript code?


Solution

  • sarsnake,

    question 1: just simple foreach in razor will do the job

    in the view

    @model IEnumerable<SomeObject>
    
    @foreach (var item in Model) {
       <div>@Html.DisplayFor(modelItem => item.Name)</div>
    }
    

    question 2: in the controller, use JsonResult to return Json representation of that array. Then you should be able to use javsacript to consume the object