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

tran huy 0 Reputation points
2024-09-04T07:26:26.52+00:00

At the first time, I used like this and it worked well, there is no error about this:

(Controller)

public ActionResult EditNV(int? id)

    {

         

        var nhanVien = db.NhanViens.Include(nv => nv.LichSus).FirstOrDefault(nv => nv.MSNV == id);

        if (id == null)

        {

            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

        }

       

        if (nhanVien == null)

        {

            return HttpNotFound();

        }

        ViewBag.ChucDanhs = new SelectList(db.ChucDanhs.Select(u => u.Ten).ToList());

        ViewBag.DonVis = new SelectList(db.DonVis.Select(u => u.TenDonVi).ToList());

        return View(nhanVien);

    }

(View: Edit)

<div class="form-group">

    @Html.Label("Đơn vị làm việc", htmlAttributes: new { @class = "control-label col-md-2" })

    <div class="col-md-10">

        @Html.DropDownList("TenDonVi", ViewBag.DonVis as SelectList, new { @class = "form-control" })

        @Html.ValidationMessageFor(model => model.TenDonVi, "", new { @class = "text-danger" })

    </div>

</div>

But when I want to use like that at the second time, and got error: There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'TenDonVi'.

Here is my second code about that:

(Controller)

public ActionResult Search(string searchString, DateTime? fromDate, DateTime? toDate)

    {

        // Truy vấn dữ liệu từ cơ sở dữ liệu

        var nhanViens = db.NhanViens.AsQueryable();

        ViewBag.DonVis = new SelectList(db.DonVis.Select(u => u.TenDonVi).ToList());

        // Lọc theo từ khóa tìm kiếm

        if (!string.IsNullOrEmpty(searchString))

        {

            searchString = searchString.Trim().ToLower();

            nhanViens = nhanViens.Where(nv => nv.TenNV.ToLower().Contains(searchString) ||

                                               nv.ChucDanh.ToLower().Contains(searchString) ||

                                               nv.MaSo.ToLower().Contains(searchString) ||

                                               nv.TenDonVi.ToLower().Contains(searchString) ||

                                               nv.CCCD.ToLower().Contains(searchString));

        }

        // Lọc theo khoảng thời gian

        if (fromDate.HasValue)

        {

            nhanViens = nhanViens.Where(nv => nv.NgayNhanViec >= fromDate.Value);

        }

        if (toDate.HasValue)

        {

            nhanViens = nhanViens.Where(nv => nv.NgayNhanViec <= toDate.Value);

        }

        // Trả về kết quả tìm kiếm

        return View("IndexNV", nhanViens.ToList());

    }

(View: Index)

<div class="form-group">

@Html.Label("Đơn vị làm việc", htmlAttributes: new { @class = "control-label col-md-2" })

<div class="col-md-10">

    @Html.DropDownList("TenDonVi", ViewBag.DonVis as SelectList, new { @class = "form-control" })

</div>

</div>

I didn't paste irrelevant code because it would be very long. I really don't know how to fix this, I just use same code as used, the different is I used at other view. Please help me, I tried in other way like just like not use ViewBag, just used transmitting directly from the database but it still doesn't work.

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,459 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,858 questions
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 28,056 Reputation points
    2024-09-04T10:27:03.3033333+00:00

    The Dropdownlist helper throw this error when it cannot find a list of select options. The Dropdownlist constructor overload you used looks for a ViewData dictionary key with the same name as the Dropdownlist when the option list passed to the constructor is null. You named the Dropdownlist "TenDonVi". There is no ViewData dictionary item named "TenDonVi" and why you see the error message "There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'TenDonVi'."

    https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.dropdownlist?view=netframework-4.8.1

    The first thing you should do is set a break point where the ViewBag.DonVis is populated. I'm guessing ViewBag.DonVis is null. You'll need to figure out why it's null. Typically on the forum we see developers will populate the options in the GET action but not POST. You must populate the options in GET and the POST.

    The follow code examples illustrate how to produce the error as well as successfully populate the options..

            public ActionResult Index()
            {
                //Working example
                //List<int> TenDonVi = new List<int>() { 1, 2, 3, 4, 5 };
                //ViewBag.TenDonVi = new SelectList(TenDonVi);
    
                //Error 
                ViewBag.TenDonVi = null;
    
                //Empty dropdown
                //List<int> TenDonVi = new List<int>();
                //ViewBag.TenDonVi = new SelectList(TenDonVi);
    
    
                return View();
            }
    
    
    

    Markup

    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    <div>
        @Html.DropDownList("TenDonVi", ViewBag.DonVis as SelectList)
    </div>
    
    
    0 comments No comments

  2. Lan Huang-MSFT 29,246 Reputation points Microsoft Vendor
    2024-09-05T03:21:53.32+00:00

    Hi @tran huy,

    You need to get the data in the GET method and then fill the data. The error occurs because you did not assign a value to ViewBag.DonVis in the GET method, and ViewBag.DonVis is NULL.

    The first time there was no error, it may be because you assigned a value to ViewBag.DonVis in the GET method.

    You need to assign a value when the page is just loaded (in the Index GET method), for example:

     public ActionResult Index()
     {         
         ViewBag.DonVis = new SelectList(db.TBL_Table1.Select(u => u.Tableid).ToList());
         return View();
     }
    
     public ActionResult Edit()
     {         
         ViewBag.DonVis = new SelectList(db.TBL_Table1.Select(u => u.Tableid).ToList());
         return View();
     }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.