当收集提交回控制器获取对象引用未设置到对象的实例。错误 [英] when collection is submitted back to controller get Object reference not set to an instance of an object. error

查看:131
本文介绍了当收集提交回控制器获取对象引用未设置到对象的实例。错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我更新多条记录,我点击提交按钮后,我得到的错误,这表明控制器接收空,并在第36行报告以下错误
下面是code代表我的控制器,视图和模型。


  

对象引用未设置到对象的实例。
          说明:


  
  

当前Web请求的执行过程中发生未处理的异常。请检查堆栈跟踪
  有关该错误的详细信息以及它起源于
  code。
           异常详细信息:System.NullReferenceException:未将对象引用设置到对象的实例


 源错误:    第34行:公众的ActionResult UpdateAll(ICollection的<&TEST0 GT; test0s)
    第35行:{
    36号线:的foreach(在test0s VAR TST)
    37号线:{
    38号线:如果(ModelState.IsValid)    源文件:C:\\用户\\ rsc_vok \\文档\\ Visual Studio 2010的\\项目\\ MvcTest0 \\ MvcTest0 \\ \\控制器线Test0Controller.cs:36

下面是模型:

 命名空间MvcTest0.Models
{
    公共类TEST0
    {
        公众诠释ID {搞定;组; }
        公众诠释SectnID {搞定;组; }
        公共字符串第{搞定;组; }
        公共字符串评论{搞定;组; }
    }    公共类Test0DBContext:的DbContext
    {
        公共DbSet<&TEST0 GT; Test0s {搞定;组; }
    }
}

这是我的控制器code:

 公众的ActionResult UpdateAll(INT ID = 0)
    {
        INT sectnid = ID;
        清单<&TEST0 GT;记录= db.Test0s.ToList();
        VAR Sectnrecord =从记录ř
                        其中,r.SectnID == sectnid
                        选择R;        返回查看(Sectnrecord.ToList());
    }    [HttpPost]
    公众的ActionResult UpdateAll(ICollection的<&TEST0 GT; test0s)
    {
        的foreach(在test0s VAR TST)
        {
            如果(ModelState.IsValid)
            {
                db.Entry(TST).STATE = EntityState.Modified;
            }
        }
        db.SaveChanges();        返回查看(test0s);
    }

这是我的看法。

  @model IEnumerable的< MvcTest0.Models.Test0>      @ {
      ViewBag.Title =UpdateAll;
     }    <脚本的src =@ Url.Content(〜/脚本/ jQuery的-1.5.1.min.js)TYPE =文/ JavaScript的>< / SCRIPT>
    <脚本的src =@ Url.Content(〜/脚本/ jquery.validate.min.js)TYPE =文/ JavaScript的>< / SCRIPT>
    <脚本的src =@ Url.Content(〜/脚本/ jquery.validate.unobtrusive.min.js)TYPE =文/ JavaScript的>< / SCRIPT>   @using(Html.BeginForm())
   {
       @ Html.ValidationSummary(真)       VAR sectnHeader =新的String [10];
       sectnHeader [0] =A.质量;
       sectnHeader [1] =B. VR转诊;
       变种项= Model.ToArray();
       变种段= 1;
       对于(VAR sectnLoop = 0; sectnLoop<段; sectnLoop ++)
       {
            <表>
                &所述; TR>
                    &所述; TD>
                        < B> @(sectnHeader [sectnLoop])LT; / B>
                    < / TD>
                < / TR>
            < /表>
            <表>
                &所述; TR>
                    <第i SectnID< /第i
                    <第i个章节< /第i
                    <第i个评论< /第i
                < / TR>            < /表>
           对于(VAR I = sectnLoop * 2; I< sectnLoop * 2 + 2;我++)
           {
               VAR sctnid =sectnname+我;
               @ Html.HiddenFor(M = GT;项目[I] .ID)
               @ Html.HiddenFor(M = GT;项目[I] .SectnID)               <表>
                  &所述; TR>
                    &所述; TD>
                        @ Html.DisplayFor(M = GT;项目[I] .SectnID)
                    < / TD>
                    &所述; TD>
                        @ Html.EditorFor(M = GT;项目[I] .SECTION)
                        @ Html.ValidationMessageFor(M = GT;项目[I] .SECTION)
                    < / TD>
                    &所述; TD>
                        @ Html.EditorFor(M = GT;项目[I]的.comment)
                        @ Html.ValidationMessageFor(M = GT;项目[I]的.comment)
                    < / TD>
                 < / TR>
                < /表>
           }
       }
        &所述p为H.;
            <输入类型=提交值=保存/>
        &所述; / P>
   }


解决方案

解决方案:


  1. 您必须将视图模型改变为支持集合类型。新增()方法:

    @model名单< MvcTest0.Models.Test0>


  2. 更改所有 @Html .___对于()助手这样的:

      @ Html.HiddenFor(M = GT; M [​​] .ID)
    @ Html.HiddenFor(M = GT; M [​​] .SectnID)
    @ Html.DisplayFor(M = GT; M [​​] .SectnID)
    @ Html.EditorFor(M = GT; M [​​] .SECTION)
    @ Html.ValidationMessageFor(M = GT; M [​​] .SECTION)
    @ Html.EditorFor(M = GT; M [​​]的.comment)
    @ Html.ValidationMessageFor(M = GT; M [​​]的.comment)


注意模型在后回重新创建和IEnumerable没有方法将项目添加到自己,不像一般的列表。

I am updating multiple records and after I click submit button I get the error, which indicates that controller receives NULL and reports the following error at line 36 Below is the code for my controller, view and the model.

Object reference not set to an instance of an object. Description:

An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

    Source Error: 

    Line 34:         public ActionResult UpdateAll(ICollection<Test0> test0s)
    Line 35:         {
    Line 36:             foreach (var tst in test0s)
    Line 37:             {
    Line 38:                 if (ModelState.IsValid)

    Source File: c:\users\rsc_vok\documents\visual studio 2010\Projects\MvcTest0\MvcTest0\Controllers\Test0Controller.cs    Line: 36

Here is the model:

namespace MvcTest0.Models
{
    public class Test0
    {
        public int id { get; set; }
        public int SectnID { get; set; }
        public string Section { get; set; }
        public string Comment { get; set; }
    }

    public class Test0DBContext : DbContext
    {
        public DbSet<Test0> Test0s { get; set; }
    }
}

And here is my controller code:

    public ActionResult UpdateAll(int id=0)
    {
        int sectnid = id;
        List<Test0> records = db.Test0s.ToList();
        var Sectnrecord = from r in records
                        where r.SectnID == sectnid
                        select r;

        return View(Sectnrecord.ToList());
    }

    [HttpPost]
    public ActionResult UpdateAll(ICollection<Test0> test0s)
    {
        foreach (var tst in test0s)
        {
            if (ModelState.IsValid)
            {
                db.Entry(tst).State = EntityState.Modified;
            }
        }
        db.SaveChanges();

        return View(test0s);
    }

And here is my view

      @model IEnumerable<MvcTest0.Models.Test0>

      @{
      ViewBag.Title = "UpdateAll";
     }

    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>

   @using (Html.BeginForm())
   {
       @Html.ValidationSummary(true)

       var sectnHeader = new String[10];
       sectnHeader[0] = "A. QUALITY";
       sectnHeader[1] = "B. VR REFERRAL";
       var items = Model.ToArray();
       var sections = 1;
       for (var sectnLoop = 0; sectnLoop < sections; sectnLoop++)
       {
            <table>
                <tr>
                    <td>
                        <b>@(sectnHeader[sectnLoop])</b>
                    </td>
                </tr>  
            </table>
            <table>
                <tr>
                    <th>SectnID</th>
                    <th>Section</th>
                    <th>Comment</th>
                </tr>

            </table>
           for (var i = sectnLoop * 2; i < sectnLoop * 2 + 2; i++)
           {
               var sctnid = "sectnname" + i;
               @Html.HiddenFor(m => items[i].id)
               @Html.HiddenFor(m => items[i].SectnID)

               <table>
                  <tr>
                    <td>
                        @Html.DisplayFor(m => items[i].SectnID)
                    </td>
                    <td>
                        @Html.EditorFor(m => items[i].Section)
                        @Html.ValidationMessageFor(m => items[i].Section)
                    </td>
                    <td>
                        @Html.EditorFor(m => items[i].Comment)
                        @Html.ValidationMessageFor(m => items[i].Comment)
                    </td>
                 </tr>
                </table> 
           } 
       } 
        <p>
            <input type="submit" value="Save" />
        </p>
   }

解决方案

Solution:

  1. You have to change the view model to a collection type which support .Add() method:

    @model List<MvcTest0.Models.Test0>

  2. Change all the @Html.___For() helpers like:

    @Html.HiddenFor(m => m[i].id)
    @Html.HiddenFor(m => m[i].SectnID)
    @Html.DisplayFor(m => m[i].SectnID)
    @Html.EditorFor(m => m[i].Section)
    @Html.ValidationMessageFor(m => m[i].Section)
    @Html.EditorFor(m => m[i].Comment)
    @Html.ValidationMessageFor(m => m[i].Comment)
    

Notice that model has to be recreated in post back and IEnumerable has no method to add items to itself, unlike generic List.

这篇关于当收集提交回控制器获取对象引用未设置到对象的实例。错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆