Hamid
Hamid

Reputation: 2088

Use IEnumerable variables in asp.net razor foreach loops

I'm declaring my variable with this code

IEnumerable<object> Update_Select_Result= null;

and assigning with this

Update_Select_Result = DB.Query(CMD_Select, Request["UpdateID"]);

but how can I use this variable in foreach?

Upvotes: 1

Views: 2608

Answers (1)

David L
David L

Reputation: 33815

First, a type OTHER than object should be used if at all possible. Build a specific class that mirrors your return output and wrap it in a List.

public class ReturnType
{
    public int UpdateId { get; set; }
    public string WhateverString { get; set; }  
}


List<ReturnType> Update_Select_Result = null;
Update_Select_Result = DB.Query(CMD_Select, Request["UpdateID"]);

Note, you will probably have to modify your data access. another option is to construct a new object from your return from the database.

At the top of your razor view, assign Model your new type

@model List<ReturnType>

Now that you have your model assigned, you can access it directly with "Model". Within your razor syntax, iterate over the collection and perform whatever magic you need to.

@foreach (var x in Model)
{
    // do whatever you need with each member of Model (List<ReturnType>), 
    // represented by x

}

Upvotes: 1

Related Questions