Home > Enterprise >  Bind Dropdownlist with ViewBag in .Net Core
Bind Dropdownlist with ViewBag in .Net Core

Time:03-12

I am trying to bind dropdownlist in Create.cshtml with ViewBag data from controller, but I got the error message as below:

An unhandled exception occurred while processing the request. ArgumentNullException: Value cannot be null. (Parameter 'items') Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList..ctor(IEnumerable items, string dataValueField, string dataTextField, IEnumerable selectedValues, string dataGroupField)

Stack Query Cookies Headers Routing ArgumentNullException: Value cannot be null. (Parameter 'items') Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList..ctor(IEnumerable items, string dataValueField, string dataTextField, IEnumerable selectedValues, string dataGroupField) Microsoft.AspNetCore.Mvc.Rendering.SelectList..ctor(IEnumerable items, string dataValueField, string dataTextField, object selectedValue) Microsoft.AspNetCore.Mvc.Rendering.SelectList..ctor(IEnumerable items, string dataValueField, string dataTextField) CallSite.Target(Closure , CallSite , Type , object , string , string ) System.Dynamic.UpdateDelegates.UpdateAndExecute4<T0, T1, T2, T3, TRet>(CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3) AspNetCore.Views_Home_Create.b__22_0() in Create.cshtml

My model:

public class PolicyCategory
{
    [Key]
    public int Category_id { get; set; }
    public string Category_name { get; set; }
}

Controller:

public async Task<IActionResult> Index()
{
    List<PolicyCategory> CategoryList  = new List<PolicyCategory>();
    
    var myList  = (from c in _context.PolicyCategory
                        select new SelectListItem()
                        {
                            Value= c.Category_id.ToString(),
                            Text=c.Category_name
                        }).ToList();
    myList.Insert(0, new SelectListItem {Value = string.Empty, Text = "Select" });
    
    ViewBag.Category = myList;
    return View(await _context.Policy.ToListAsync());
}

View:

<div >
    <label asp-for="Category" ></label>
    <select name="Category" 
            asp-for="Category " 
            asp-items="@(new SelectList(ViewBag.Category,"Value","Text"))">
    </select>
    <span asp-validation-for="Category" ></span>
</div>

Where the problem is? Thanks.

CodePudding user response:

Viewbag isn't the best mode of binding data with .NET core. It is best to use a ViewModel.

  1. Set the binding in the code backend.

       [BindProperty]
       public List<SelectListItem> Categories { get; set; }
    
  2. Return the Data in the Controller

    Categories = myList;
    
    return Page();
    
  3. Bind the Data from ViewModel in your markup

    <select id="ddlCategories" name="Categories" asp-items="@Model.Categories">
             <option value="@Model.Value">@Model.Text</option>
         </select>
    

That should do

CodePudding user response:

I solved my problem with this example https://syntaxfix.com/question/3985/select-tag-helper-in-asp-net-core-mvc. My problem was in the modelview class, add

  [NotMapped]
        public List<PolicyCategory> Categories { get; set; }

in controller, add the Categories to the PolicyViewModel
PolicyViewModel vm = new  PolicyViewModel();
        
List<SelectListItem> Categories = new List<SelectListItem>();
vm.Categories = (from c in _context.PolicyCategory
                         select c
                         ).ToList();
                        
return View(vm);
  • Related