RuntimeBinderException:无法对空引用执行运行时绑定

时间:2019-10-16 16:06:29

标签: c# asp.net asp.net-mvc visual-studio asp.net-core

我正在创建一个创建项目页面,在此创建项目页面中,有一个弹出模式表,我们可以在其中选择所需的UoM类型。通常,当提交此表单并填写所有字段时,它将值保存到数据库中。但是,在提交表单时未填写一个或一些或所有字段的情况下,它会给出一些错误消息,提示必须填写这些字段。但是没有,它显示了此错误。

enter image description here

这些是我的代码

ItemController

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Threading.Tasks;
using CRMandOMS.Models;
using CRMandOMS.ViewModels;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace CRMandOMS.Controllers
{
    public class ItemController : Controller
    {
        private readonly IItemRepository _itemRepository;

        private readonly IUoMRepository _uoMRepository;

        public ItemController(IItemRepository itemRepository, IUoMRepository uoMRepository)
        {
            _itemRepository = itemRepository;
            _uoMRepository = uoMRepository;
        }

        // GET: /<controller>/
        public ViewResult Index()
        {
            var model = _itemRepository.GetAll();

            return View(model);
        }

        public ViewResult Details(Guid? id)
        {
            Item item = _itemRepository.GetById(id.Value);

            return View(item);
        }

        [HttpGet]
        public ViewResult Create()
        {
            ItemCreateViewModel itemCreateViewModel = new ItemCreateViewModel()
            {
                UoMs = _uoMRepository.GetAll()
            };

            return View(itemCreateViewModel);
        }

        [HttpPost]
        public IActionResult Create(ItemCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                Item newItem = new Item
                {
                    Name = model.Name,
                    Price = model.Price,
                    UoMId = model.UoMId
                };

                _itemRepository.Insert(newItem);

                return RedirectToAction("Details", new { id = newItem.Id });
            }

            return View();
        }
    }
}

创建

@model CRMandOMS.ViewModels.ItemCreateViewModel

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

<h2>Item Create</h2>

<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item"><a asp-controller="Item" asp-action="Index">Item</a></li>
        <li class="breadcrumb-item active" aria-current="page">Create</li>
    </ol>
</nav>

<form enctype="multipart/form-data" asp-controller="Item" asp-action="Create" method="post" class="mt-3">

    <div class="form-group row">
        <label asp-for="Name" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="Name" class="form-control" placeholder="Name" />
            <span asp-validation-for="Name" class="text-danger"></span>
        </div>
    </div>

    <div class="form-group row">
        <label asp-for="Price" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="Price" class="form-control" placeholder="Price" />
            <span asp-validation-for="Price" class="text-danger"></span>
        </div>
    </div>

    <div class="form-group row">
        <label asp-for="UoMId" class="col-sm-2 col-form-label"></label>
        <div class="col-sm-10">
            <input asp-for="UoMId" id="uomid" class="form-control" hidden />
            <div class="input-group mb-3">
                <input id="uomname" type="text" class="form-control" placeholder="UoM" aria-label="UoM" aria-describedby="button-uom" disabled>
                <div class="input-group-append">
                    <button class="btn btn-outline-success" type="button" id="button-uom" data-toggle="modal" data-target="#uoMLookupTableModal">Select UoM</button>
                </div>
            </div>
            <span asp-validation-for="UoMId" class="text-danger"></span>
        </div>
    </div>

    <div asp-validation-summary="All" class="text-danger"></div>

    <div class="form-group row">
        <div class="col-sm-2"></div>
        <div class="col-sm-10">
            <a asp-controller="Item" asp-action="Index" class="btn btn-light">Back</a>
            <button type="submit" class="btn btn-success">Create</button>
        </div>
    </div>
</form>

@{
    await Html.RenderPartialAsync("_UoMLookup");
}

@section scripts {
    <script>
        $(document).ready(function () {
            var uoMTable = $("#uoMTable").DataTable({
                "columnDefs": [
                    {
                        "targets": [0],
                        "visible": false
                    }
                ],
                "order": [[1, "asc"]]
            });

            $('#uoMTable tbody').on('click', 'tr', function () {
                if ($(this).hasClass('table-success')) {
                    $(this).removeClass('table-success');
                }
                else {
                    uoMTable.$('tr.table-success').removeClass('table-success');
                    $(this).addClass('table-success');
                }
            });

            $("#getUoM").click(function () {
                var uomdata = uoMTable.row('.table-success').data();

                //alert(uomdata[0]);
                $('#uomid').val(uomdata[0]);

                //alert(uomdata[1]);
                $('#uomname').val(uomdata[1]);
            });
        });
    </script>
}

_UoMLookup

<div class="modal fade" id="uoMLookupTableModal" tabindex="-1" role="dialog" aria-labelledby="uoMLookupTableModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <table id="uoMTable" class="table table-striped table-bordered table-bordered nowrap" style="width:100%">
                    <thead>
                        <tr>
                            <td>Id</td>
                            <td>Name</td>
                            <td>Description</td>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (UoM uom in Model.UoMs)
                        {
                            <tr>
                                <td class="uom-id">@uom.Id</td>
                                <td class="uom-name">@uom.Name</td>
                                <td>@uom.Description</td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light" data-dismiss="modal">Cancel</button>
                <button id="getUoM" type="button" class="btn btn-success" data-dismiss="modal">Select</button>
            </div>
        </div>
    </div>
</div>

ItemCreateViewModel

using CRMandOMS.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace CRMandOMS.ViewModels
{
    public class ItemCreateViewModel
    {
        [Required]
        [MaxLength(100, ErrorMessage = "Name cannot exceed 100 characters")]
        public string Name { get; set; }

        [Required(ErrorMessage = "{0} is required")]
        [Range(1000, 999999999)]
        public int Price { get; set; }

        [Required]
        public Guid UoMId { get; set; }
        public IEnumerable<UoM> UoMs { get; set; }

        public string PhotoPath { get; set; }
    }
}

2 个答案:

答案 0 :(得分:0)

HTTP POST Create方法(ItemController)中,如果模型无效(所以ModelState.IsValid == false),则没有将模型传递给View。确保传递有效的模型,如controller methods tutorial所示。

答案 1 :(得分:0)

  

但是,当提交表单时未填写一个或一些或所有字段时,它会给出一些错误消息,提示必须填写这些字段。但是没有,它显示了此错误。

您没有引用验证脚本,请确保您在_ValidationScriptsPartial.cshtml文件夹中有Shared,然后修改代码:

@section scripts {
  @{await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
  <script>
  //...
  </script>
}

对于页面上的错误,就像其他社区所说的那样,很可能模型状态无效并且它执行return View()而不返回任何数据来创建视图。

但是,您的部分视图不允许Model.UoMs为空。

在创建Post操作中,如果model包含UoMs,则可以使用

return View(model)

否则,将UoMs数据分配为模型,就像您在“创建Get”操作中所做的那样,然后将其返回查看。

您随时可以在Post操作上使用断点来调试结果。