简体   繁体   中英

"ArgumentNullException: Value cannot be null. (Parameter 'items')" using a dropdown in the view asp.net mvc to create new database records

I am getting the error "ArgumentNullException: Value cannot be null. (Parameter 'items')" when I try to create new database records. I am able to edit database records in asp.net MVC 5 but not create them.

My model is:

using System.ComponentModel.DataAnnotations.Schema;

namespace Speakers2.Models
{
    [Table("SpeakerStatus", Schema = "SalesOps")]
    public partial class SpeakerStatusLookupModel
    {
        public int Id { get; set; }
        public string SpeakerStatus { get; set; }
    }
}

The context is:

using Microsoft.EntityFrameworkCore;
using Speakers2.Models;

namespace Speakers2.Data
{
    public class Speakers2Context : DbContext
    {
        public Speakers2Context(DbContextOptions<Speakers2Context> options)
            : base(options)
        {
        }

        public DbSet<SpeakerStatusLookupModel> SpeakerStatusLookupModel { get; set; }
    }
}

The view is:

@model Speakers2.Models.SpeakerQuery

@{
    ViewData["Title"] = "Create";
}

<h1>Create</h1>

<h4>Speaker</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">   
                <label asp-for="SpeakerStatus" class="control-label"></label>
                <select asp-for="SpeakerStatus" class="control-label" asp-items="@(new SelectList(@ViewBag.statusTypeList, "Id", "SpeakerStatus"))"></select>
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

The problem is that the <select asp-for="SpeakerStatus" class="control-label" asp-items="@(new SelectList(@ViewBag.statusTypeList, "Id", "SpeakerStatus"))"></select> expects an ID which I don't have since I am creating a new record.

I set the @ViewBag.statusTypeList in:

List<SpeakerStatusLookupModel> statusTypeList = new();
            statusTypeList = (from SpeakerStatus in _context.SpeakerStatusLookupModel select SpeakerStatus).ToList();
            statusTypeList.Insert(0, new SpeakerStatusLookupModel { Id = 0, SpeakerStatus = "Select" });
            ViewBag.statusTypeList = statusTypeList;

我发现了问题 - 我在控制器的“编辑”部分中有 @ViewBag.statusTypeList 代码,但在“创建”部分没有,所以当我尝试创建新记录时它是 NULL。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM