解决ASP.NET MVC5"无法对 null 引用执行运行时绑定"

无法对 null 引用执行运行时绑定

说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 
异常详细信息: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 无法对 null 引用执行运行时绑定
源错误: 

视图,Demo.csthml:

  1. @model LanhuImageUploader.Web.Models.Product
  2. @{
  3. ViewBag.Title = "Demo";
  4. }
  5. @Html.Action("ScriptCommon", "Common")
  6. <div class="pop-win">
  7. <div id="check-order">
  8. <div class="row" style=" margin-top:30px;">
  9. <span class="field"> 商品图片: </span>
  10. <span><input type="button" class="btn btn-primary" style="padding-left:18px;" value="添加图片" page="ProImages" onclick="addPageImg(this)" /></span>
  11. <input type="hidden" id="hidProImages" name="ADPicUrl" value="@Model.ADPicUrl" />
  12. <input type="hidden" id="hidProImages" name="ADPicUrl" value="" />
  13. </div>
  14. <div class="row">
  15. <table class="produtImageThumb">
  16. <tr pre="imgtr" id="imgtr-ProImages" style="display:none"><td colspan="2"></td></tr>
  17. </table>
  18. </div>
  19. </div>
  20. </div>
  21. @Html.Action("UploadImage", "Common")
  22. <script>
  23. $(function () {
  24. });
  25. </script>

这种情况一般是返回视图的时候没有传model对象才会报错,如下:

  1. public ActionResult Demo()
  2. {
  3. return View();
  4. }

解决办法:

在Action中当返回View的时候,传一个默认的model给它如下:

    1. public ActionResult Demo()
    2. {
    3. var m = new LanhuImageUploader.Web.Models.Product();
    4. return View(m);
    5. }
原文地址:https://www.cnblogs.com/objectnull/p/9240160.html