在 .Net Core 中使用 ViewBag 绑定下拉列表

Bind Dropdownlist with ViewBag in .Net Core

我正在尝试将 Create.cshtml 中的下拉列表与来自控制器的 ViewBag 数据绑定,但我收到如下错误消息:

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 +

我的模特:

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

控制器:

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());
}

查看:

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

问题出在哪里?谢谢。

Viewbag 不是将数据与 .NET 核心绑定的最佳模式。最好使用 ViewModel。

  1. 在代码后端设置绑定。

       [BindProperty]
       public List<SelectListItem> Categories { get; set; }
    
  2. Return控制器中的数据

    Categories = myList;
    
    return Page();
    
  3. 在您的标记中绑定来自 ViewModel 的数据

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

应该可以

我用这个例子解决了我的问题https://syntaxfix.com/question/3985/select-tag-helper-in-asp-net-core-mvc。我的问题出在模型视图 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);