【问题标题】:RuntimeBinderException: Cannot perform runtime binding on a null referenceRuntimeBinderException:无法对空引用执行运行时绑定
【发布时间】:2020-02-13 11:35:09
【问题描述】:

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

这些是我的代码

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

【问题讨论】:

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


    【解决方案1】:

    HTTP POST Create 方法 (ItemController) 中,如果模型无效(因此 ModelState.IsValid == false),您没有将模型传递给您的视图。确保传递一个有效的模型,如controller methods tutorial所示。

    【讨论】:

      【解决方案2】:

      但是,当提交的表单中的一个或部分或所有字段未填写时,它应该会给出一些字段是必需的错误消息。但它没有,它显示了这个错误。

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

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

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

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

      在您的 Create Post 操作中,如果 model 包含 UoMs,您可以使用

      return View(model)
      

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多