0

I want to get the selected dropdownlist value in the controller.

It gives the following error

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'studentid'

Controller code

[HttpGet]
public ActionResult CallSqlScalarFuction()
{
    IList<int> StudentIDs = db.Students.Select(x => x.ID).ToList();
    ViewBag.studentid = StudentIDs.Select(x => new SelectListItem()
    {
        Text = x.ToString(),
        Value = x.ToString()
     });
     return View();
 }

[HttpPost]
public ActionResult CallSqlScalarFuction(int studentid)
{
    string sql = @"Select dbo.GetStudentNameById(@p0) as FullName";
    var studentFullName = db.Database.SqlQuery<string>(sql, studentid).ToList();
    ViewBag.studentFullName = studentFullName[0].ToString();
    return View();
}

CallSqlScalarFuction.cshtml

@using (Html.BeginForm("CallSqlScalarFuction", "Students",FormMethod.Post,null))
{
    @Html.Label("Please select StudentID:")
    @Html.DropDownList("studentid", (IEnumerable<SelectListItem>)ViewBag.studentid)
    <input type="submit" value="submit" class="btn btn-primary" />
}
vicky
  • 241
  • 1
  • 3
  • 12
  • please ignore the last line having input type="submit". – vicky Apr 17 '16 at 10:16
  • Assuming that 2nd submit button is a typo, the then in the POST method, the value of `studentid` will be the selected option value. –  Apr 17 '16 at 10:17
  • @StephenMuecke: i expect it to be so. but its not working...it gives error like this: There is no ViewData item of type 'IEnumerable' that has the key 'studentid' – vicky Apr 17 '16 at 10:20
  • It is. But the error is because you have not re-assigned the `SelectList` when you return the view (as you did in the GET method) –  Apr 17 '16 at 10:22
  • Identical to the dupe, just a different error message because of your (awful) use of `DropDownList()` rather that the strongly typed `DropDownListFor()` method. –  Apr 17 '16 at 10:26
  • @StephenMuecke: thanks a lot.. your suggestion worked :). but for this I had to duplicate the code used in GET method and put it in POST method. Is there any way out on how to avoid re-assigning the viewbag data again in the post method? – vicky Apr 17 '16 at 10:30
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/109367/discussion-between-stephen-muecke-and-user1829056). –  Apr 17 '16 at 10:32
  • i m not using viewmodels for the view, so i think DropdownlistFor() method cant be used. is it ? – vicky Apr 17 '16 at 10:32
  • Then start using one :) –  Apr 17 '16 at 10:38

0 Answers0