我正在嘗試將下拉串列Create.cshtml與ViewBag來自控制器的資料系結,但我收到如下錯誤訊息:
處理請求時發生未處理的例外。ArgumentNullException:值不能為空。(引數“專案”)Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList..ctor(IEnumerable 專案,字串 dataValueField,字串 dataTextField,IEnumerable selectedValues,字串 dataGroupField)
堆疊查詢 Cookie 標頭路由 ArgumentNullException:值不能為空。(引數“專案”)Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList..ctor(IEnumerable 專案,字串 dataValueField,字串 dataTextField,IEnumerable selectedValues,字串 dataGroupField)Microsoft.AspNetCore.Mvc.Rendering.SelectList..ctor(IEnumerable 專案,字串 dataValueField, 字串 dataTextField, 物件 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 站點, 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>
問題出在哪里?謝謝。
uj5u.com熱心網友回復:
Viewbag 不是與 .NET 核心系結資料的最佳模式。最好使用 ViewModel。
在代碼后端設定系結。
[BindProperty] public List<SelectListItem> Categories { get; set; }回傳控制器中的資料
Categories = myList; return Page();在標記中系結來自 ViewModel 的資料
<select id="ddlCategories" name="Categories" asp-items="@Model.Categories"> <option value="@Model.Value">@Model.Text</option> </select>
那應該做
uj5u.com熱心網友回復:
我用這個例子解決了我的問題https://syntaxfix.com/question/3985/select-tag-helper-in-asp-net-core-mvc。我的問題是在模型視圖類中,添加
[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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/442057.html
