Amir Nassal
Amir Nassal

Reputation: 441

Can't display data from the ViewBag

I have a table in my database and I want to get the name field without repetition. But I get this error:

'string' does not contain definition for 'ID'. When I debug my code, I find the variables full with data, until the foreach the error shows up.

In my controller:

public ActionResult Create()
{
            HREntities db = new HREntities();
            var areas = db.Area.Select(area => area.Area + area.ID).Distinct().ToList();
            if(areas != null)
                ViewBag.areas = areas;

            return View();
}

The view's code:

 @foreach (var area in ViewBag.areas)
{
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
        <input name="group4" type="radio" id="@area.ID" class="radio-col-blue-grey" />
        <label for="@area.ID">@area.Area</label>
    </div>
}

Upvotes: 1

Views: 848

Answers (2)

user3559349
user3559349

Reputation:

Your .Select() query is returning IEnumerable<string>, not a collection of Area objects (and a string does not have a property named Id)

Based on your query your view code should be just

@foreach (var area in ViewBag.areas)
{
    <div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
        <input name="group4" type="radio" id="@area" class="radio-col-blue-grey" />
        <label for="@area">@area</label>
    </div>
}

Alternativey you need to return a collection of your model

Upvotes: 1

Abbas
Abbas

Reputation: 14432

In your Create method in the controller, you are creating a List<string>on following line:

var areas = db.Area.Select(area => area.Area + area.ID).Distinct().ToList();

You then pass this list to the ViewBag, but as it is now a list of strings and not a List<Area>, it won't have an ID property there.

While debugging, check the type of the variable areas, you'll see. Your markup code in the foreach loop should look like this:

<input name="group4" type="radio" id="@area" class="radio-col-blue-grey" />
<label for="@area">@area</label>

Upvotes: 1

Related Questions