33Fraise33
33Fraise33

Reputation: 701

Dropdownlistfor MVC 5 in ListView (IEnumerable of Viewmodel)

I am making a school project and I'm stuck at a dropdownlist in my view. So here is my ViewModel:

using System;
using System.Collections.Generic;
using System.Linq;
using Klimatogrammen.Models.Domain;

namespace Klimatogrammen.ViewModels
{
    public class VraagViewModel
    {
        public String Question { get; private set; }
        public String Code { get; private set; }
        public List<double> Answers { get; private set; }

        public VraagViewModel(Parameter temp, Klimatogram klim)
        {
            Question = temp.Naam;
            Code = temp.Code;
            Answers = temp.GeefMogelijkeAntwoorden(klim).ToList();
        }

    }
}

And the related View

@model IEnumerable<Klimatogrammen.ViewModels.VraagViewModel>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Question)
        </th>
    <th>
        @Html.DisplayNameFor(model => model.Answers)
    </th>
       @Html.DropDownListFor(Model) 

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Question)
        </td>
        <td>
            @Html.DropDownListFor(new SelectList(item.Answers))
        </td>

    </tr>

}

</table>

So I want to have a list of doubles as answer to the question. Every Question has its own specific answers and I want to display them next to each question the possibilities.

I tried a few things but I couldn't find a solution (from selectlists to selectitems etc but I don't have a value or text, I just want to display the doubles). Also my view has to stay an IEnumerable (I have my reasons)

Can anyone share some light on this?

Upvotes: 2

Views: 8363

Answers (2)

33Fraise33
33Fraise33

Reputation: 701

I was actually able to fix it myself (with a friend of mine).

This is what my view contains at the moment:

@model IEnumerable<Klimatogrammen.ViewModels.VraagViewModel>
@{
    Layout = null;
}

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
@using (Html.BeginForm("Vraag", "Vraag"))
{
    @Html.ValidationSummary(true)
    <table class="table">
        <tr>
        <th>
            @Html.DisplayNameFor(model => model.Vraag)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Antwoorden)
        </th>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Vraag)
                </td>
                <td>

                    @Html.DropDownListFor(p => item.Antwoord, item.test, "--- Kies een antwoord ---")
                    @Html.ValidationMessageFor(m => item.Antwoord)

                </td>
            </tr>
        }
    </table>

    <div style="text-align:center;"><input type="submit" value="Controleer uw vragen" class="btn btn-default" /></div>
}

item.test contains a list of SelectListItemwhich are made in my model. This way I get my dropdownboxes! thanks everyone for the help ;)

The only problem left now are my validationmessages, If I don't fill in anything I get the message that I should enter something for every box. But when I fill in 1 I get forwarded when I click my button. (If I find an option for that I will add this over here too)

Upvotes: 0

JEV
JEV

Reputation: 2504

In order to do this I recommend you pass in an IEnumerable of SelectListItem to the DropDown. So add another property to your model.

...
public double Answer { get; set;}
...

And then convert your collection of double's to a collection of SelectListItem

var collection = Answers.Select(a => new SelectListItem() {Text = a.ToString(), Value = a.ToString()});

And then once you use the below helper you will be sorted and your Model.Answer will have the correct value

@Html.DropDownListFor(model => model.Answer, Model.Answers)

Further work

I recommend making an Enumerable extension which can take in some of your more complex objects and then give you your select list

public static IEnumerable<SelectListItem> ToSelectList<T>(this IEnumerable<T> enumerable) where T : ISelectList
{
    var list = enumerable.ToList();
    if (list.Any())
    {
        return list.Select(l => new SelectListItem() { Text = l.Name, Value = l.Id.ToString() });
        // We can use an interface to define that any type that 
        //has 2 properties (Name and Id) can be converted into a select list.

    }
    return Enumerable.Empty<SelectListItem>();
}

public interface ISelectList
{
    string Name { get; set; }
    int Id { get; set; }
}

And if you want an awesome one liner for next time you can use this:

var list = new SelectList(Answers.Select(x=>new KeyValuePair<string,string>(x.ToString(),x.ToString())), "Key", "Value");

Upvotes: 2

Related Questions