[英]When assigning value into an Array it returned Object reference not set to an instance of an object
So basically I am trying to get the value from the database and form it into a list so that I can assign each one of them to a dynamic input tag.所以基本上我试图从数据库中获取值并将其形成一个列表,以便我可以将它们中的每一个分配给一个动态输入标签。
View看法
@foreach (var item in (List<SelectListItem>)ViewBag.AppendTab)
{
@Html.TextBoxFor(m => m.Name[Convert.ToInt32(item.Text)],
new { id = "txtName-" + item.Value, placeholder = "", @class = "form-control"})
@Html.TextBoxFor(m => m.PhoneNo[Convert.ToInt32(item.Text)],
new { id = "txtPhoneNo-" + item.Value, placeholder = "", @class = "form-control"})
/* And Many others field */
}
Controller Controller
List<Student> Model = _StudentBLL.GetAll(SchoolId); // Action that gets the list
if (Model.Count != 0)
{
int counter = 0;
foreach (var item in Model)
{
view.Name[counter] = item.Name;
view.PhoneNo[counter] = item.PhoneNo;
counter++;
}
}
@Beingnin It is referring to this line
view.Name[counter] = item.Name;
@Beingnin 指的是这一行view.Name[counter] = item.Name;
– FENR1R Ace 2 hours agoView.Name
is not null – FENR1R Ace 1 hour ago – FENR1R Ace 2 小时前View.Name
不是 null – FENR1R Ace 1 小时前
If nothing on the left hand side of the = is null then it must be that your GetAll
put a null thing in the Model.如果 = 的左侧没有任何内容是 null,那么一定是您的GetAll
中放置了 null 东西。 This model, for example, will also crash with a null reference in the same way:例如,这个 model 也会以同样的方式与 null 引用一起崩溃:
List<Student> Model = new List<Student>();
Model.Add(null);
How it gets there, is for you to figure out.. You could just exclude them:它是如何到达那里的,由您自己弄清楚。您可以将它们排除在外:
foreach (var item in Model.Where(s => s != null))
.. but you should try and find out why they're happening in the first place, so it doesn't trip you up elsewhere in the code when you use GetAll again. .. 但是您应该首先尝试找出它们发生的原因,因此当您再次使用 GetAll 时,它不会在代码的其他地方绊倒您。
Ultimately, NullRef exceptions are typically very easy to debug;归根结底,NullRef 异常通常很容易调试; the code crashes and stops, the debugger opens and you just point to every word, or select highlight every expression and then point to it, on the line with your mouse, see which one makes the tooltip say "null".代码崩溃并停止,调试器打开,您只需指向每个单词,或者 select 突出显示每个表达式,然后用鼠标指向它,看看哪个使工具提示显示为“null”。 You can also open the immediate window and paste bits of the code line into it and run it, looking for where it says null, eg pasting ?item
into it should say null
in your case您也可以立即打开 window 并将代码行的位粘贴到其中并运行它,查找它显示 null 的位置,例如将?item
粘贴到其中应该说null
在您的案例中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.