Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi. I tried to search data by using dropdownlist but i get error there is no viewdata item of type IEnumerable<selectlistitem> That has the key ‘id’

I am referring this tutorial
https://youtu.be/6X4pZW3onP8

but i dont really understand why they use post function in the video for the dropdown list.

Ive search the error. It says that it is because the data is null or the system does not execute the query.

What I have tried:

In view:
@model IEnumerable<SearchFunctionDemo.Models.TesterModel>

@using (Html.BeginForm())
{
@Html.DropDownList("id", null, htmlAttributes: new { @class="form-control"})
<input type="Submit" value="Search">
}

@foreach(var item in ViewBag.TesterID)
{
@item.TesterID
@item.Name
}


In controller:
Public ActionResult Index()
{
var query=(from c in db.Testers
                   select new TesterModel
                   {
                     Name=c.Name,
TesterID=c.TesterID}).ToList();
ViewBag.TesterID=query;
return View();
}

[HttpPost]
Public ActionResult Index(int id)
{
var query=(from c in db.Testers
where c.TesterID == id
select new Testeramodel
{
Name=c.Name,
TesterID=c.TesterID
}).ToList();
ViewBag.TesterID=new SelectList(query, "TesterID","Name");
}
Posted
Updated 16-Jul-20 0:06am

1 solution

You've given your DropDownList the name "id". Therefore, you need to store the SelectList in ViewBag.id.

However, the code seems rather confused. You specify a @model for the view, but you only pass the model from the HttpPost method. In one method, you store a List<TesterModel> in the ViewBag, but in the other you store a SelectList. And you don't do anything with the submitted ID.

I'd be inclined to use the HttpGet method for both requests, since you're only sending a single int value:
C#
[HttpGet]
public ActionResult Index(int? id = default)
{
    var testers = db.Testers.Select(c => new { c.TesterID, c.Name }).ToList();
    
    ViewBag.TesterList = testers.Select(c => new SelectListItem
    {
        Value = c.TesterID.ToString(),
        Text = c.Name,
        Selected = c.TesterID == id,
    });
    
    return View();
}
Razor
@using (Html.BeginForm("Index", "YourControllerName", FormMethod.Get))
{
    @Html.DropDownList("id", (IEnumerable<SelectListItem>)ViewBag.TesterList, "-Select One-", new { @class = "form-control" })
    <input type="submit" value="Search">
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900