首页 > 解决方案 > HTML 中的 Asp-Items 选择 Razor 页面。你调用的对象是空的

问题描述

我试图让一个 html 选择来填充我到目前为止的代码。并且在加载时它一直告诉我“对象引用未设置为对象的实例”并突出显示 asp=items 片段。为什么会这样?我已经确认列表确实在 get 方法的末尾填充,为什么该值没有进入页面?

屏幕:

  <div class="container">
        <h1 class="mt-4 mb-3">
            NYS Courts
            <small>Welcome</small>
        </h1>
        <hr />

        <div class="row">
            <div class="col-md-8 mb-4">
                <h3>Select Organization</h3>
                <br />
                <form asp-page="SelectOrganization" method="post" name="SelectOrganizationScreen" id="SelectOrganizationForm">
                    <div class="form-group">
                                               <select asp-for="CourtId" asp-items="@(new SelectList(Model.OrganizationSelectList,"CourtId","CourtName"))" name="CourtId" id="CourtId">
                            <option class="form-control" value="">Choose a Court</option>
                        </select>


                    </div>

                    <button type="submit"> Submit</button>
                </form>

            </div>
        </div>


    </div>

剃刀代码:

       public void OnGet()
        {
            //user will have the list of courts they have permission to access?
            //Hard coded for now
            var OrgValuePairs = new List<OrganizationSelectDTO>()
            {
               new OrganizationSelectDTO
               {
                   CourtID = "2",
                   CourtName = "Criminal Court"
               },
               new OrganizationSelectDTO
               {
                   CourtID = "3",
                   CourtName = "Supreme Court"
               },
               new OrganizationSelectDTO
               {
                   CourtID = "4",
                   CourtName = "Surrogate's Court"
               }
            };

            OrganizationSelectList = OrgValuePairs;
}
    public class OrganizationSelectDTO
    {
        public string CourtName { get; set; }

        public string CourtID { get; set; }
    }

标签: htmlasp.net-corerazor-pages

解决方案


此问题是由您的拼写错误引起的。

在您的模型中,您的属性是CourtID,但在您看来,

asp-items="@(new SelectList(Model.OrganizationSelectList,"CourtId","CourtName"))",

它是CourtId

您需要将其更改为CourtID

asp-items="@(new SelectList(Model.OrganizationSelectList,"CourtID","CourtName"))"

推荐阅读