0

when I click on my body and take a value, click the button, so when clicked on it so make this one mistake.

I've tried many things now drop down and inside behind my code but it still gives me the same error. I try the bebug and see how it happens.

The ViewData item that has the key 'SelectedOpgaveValue' is of type 'System.String' but must be of type 'IEnumerable'.

Line 48:                 
Line 49:         <div class="form-group">
Line 50:             @Html.DropDownListFor(x => x.SelectedOpgaveValue, Model.OpgaveValueList, new
Line 51:                 {
Line 52:                     @class = "form-control"

My controller:

        [MvcApplication.SessionExpire]
    [HttpGet]
    public ActionResult Index()
    {
        DataLinqDB db = new DataLinqDB();
        OpgaverPage model = new OpgaverPage();

        var random = new Random();
        var antalopgaver = db.Questions.Count();
        var number = random.Next(antalopgaver);

        //henter en random spørgsmål.
        var A = db.Questions.Where(i => i.fk_Categories == 1).Skip(number).Take(1).FirstOrDefault();
        model.Overskift = A.title;
        model.HiddenId = A.id;

        //Henter alle de svar muligheder man har til den id som man få fra A
        List<Question_Answer> QA = db.Question_Answers.Where(i => i.fk_Question == A.id).ToList();

        //dropdown her
        List<SelectListItem> items = new List<SelectListItem>();
        foreach (var item in QA.ToList())
        {
            items.Add(new SelectListItem() { Text = item.text, Value = item.id.ToString() });
        }

        //seleced dropdown
        model.OpgaveValueList = new SelectList(items, "Value", "Text");

        return View(model);
    }

    [MvcApplication.SessionExpire]
    [HttpPost]
    public ActionResult index(OpgaverPage opgavervalue)
    {
        DataLinqDB db = new DataLinqDB();
        if (ModelState.IsValid)
        {
            var opgaver = db.Question_Answers.FirstOrDefault(i => i.fk_Question == opgavervalue.HiddenId);
            if (opgaver != null)
            {
                if (opgavervalue.SelectedOpgaveValue.ToString() == opgaver.id.ToString() && opgaver.er_svaret == true)
                {
                    PointHelper.Point.PointInsert("opgaver");
                }
                else
                {
                    //error
                    ModelState.AddModelError("", "Desværre dit svar forkert");
                }
            }
            else
            {
                return RedirectToAction("index");
            }
        }
        return View(opgavervalue);
    }

Model:

public class OpgaverPage
{
    public string Overskift { get; set; }
    public int HiddenId { get; set; }
    [Display(Name ="Spørgsmål")]
    public string Svar { get; set; }
    public List<Question_Answer> QuestionList { get; set; }
    public IEnumerable<SelectListItem> OpgaveValueList { get; set; }
    public string SelectedOpgaveValue { get; set; }
}

index.cshtml

<p>@Model.Overskift</p>
@using (Html.BeginForm("index", "Opgaver"))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)
    @Html.HiddenFor(i => i.HiddenId)              
    <div class="form-group">
        // Error is here!!
        @Html.DropDownListFor(x => x.SelectedOpgaveValue, Model.OpgaveValueList, new { @class = "form-control" })
    </div>
    <button type="submit" class="btn btn-effect-ripple btn-success"><i class="fa fa-check"></i> Tjek mit svar</button>
}
3
  • It because in the POST method you return the view but have not reassigned the SelectList - i.e. model.OpgaveValueList = new SelectList(items, "Value", "Text"); as you did in the GET method Commented Dec 2, 2015 at 22:11
  • @StephenMuecke What do you completely with it? Commented Dec 2, 2015 at 22:17
  • I misunderstand you just a moment @StephenMuecke Commented Dec 2, 2015 at 22:24

1 Answer 1

0

The error occurs because when you return the view in the POST method, the value of OpgaveValueList is null (and the DropDownListFor() method falls back to the overload that expects the first parameter to be IEnumerable. You need to reassign the value of OpgaveValueList before you return the view as you did in the GET method.

Note also there is no point in the extra overhead of geerating a second IEnumerable<SelectListItem> (which is what SelectList is) from the first one. Your code can simply be

List<SelectListItem> items = new List<SelectListItem>();
foreach (var item in QA.ToList())
{
    items.Add(new SelectListItem() { Text = item.text, Value = item.id.ToString() });
}
model.OpgaveValueList = items;
return View(model);

Or even simpler

model.OpgaveValueList = QA.Select(x => new SelectListItem
{
  Text = x.text,
  Value = x.id.ToString()
};

To keep things DRY, I suggest you create a private method

private void ConfigureViewmodel(OpgaverPage model)
{
  model.OpgaveValueList = db.Question_Answers.Where(i => i.fk_Question == A.id.Select(x => new SelectListItem
  {
    Text = x.text,
    Value = x.id.ToString()
  };
}

and then in both the GET and POST methods call it before returning the view

ConfigureViewmodel(model);
return View(model);
Sign up to request clarification or add additional context in comments.

6 Comments

I have tried to do as you write and explain but it tells me still the same error unfortunately. :(
It does not. You must have made another error as well. Are you sure you have added that code in the POST method?
Where in the POST do you want the pregnant ??
I have updated the answer. And what do you mean want the pregnant?
you write like this, Are you sure you have added that code in the POST method? then I think just where would you like to want me to throw it into the post
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.