选择列表和多选列表|你调用的对象是空的。 [英] Select list and multi select list | object reference not set to an instance of an object.

查看:61
本文介绍了选择列表和多选列表|你调用的对象是空的。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好!我试图在ASP.NET(MVC5)中实现一个选择列表(DropDownListFor)和一个多选列表(ListBoxFor),当我提交表单时,我得到一个'对象引用未设置为对象的实例'异常。我找到了一堆堆栈溢出文章,这对我来说实际上并没有帮助我。我尝试了很多东西,但没有多少运气。



这是一张异常照片: [例外照片,

点击我!
]



我的尝试:



控制器:



 public ActionResult New()
{
List< string> availableImages = new List< string>();
//这里我从
获取所有可用图像的路径//数据库
foreach(图像contextImage in _context.Images)
{
availableImages。加入(contextImage.FullName);
}

返回视图(新建,新建NewProductViewModel(availableImages));
}





ViewModel:



<$ p $使用系统;
使用System.Collections.Generic;
使用System.ComponentModel.DataAnnotations;
使用System.Linq;
使用System.Web;
使用System.Web.Mvc;
使用Mom_Website.Models;

命名空间Mom_Website.ViewModels
{
公共类NewProductViewModel
{
public int Id {get;组; }

[必需]
[StringLength(40)]
公共字符串名称{get;组; }

[必需]
公共字符串描述{get;组; }

//这是将在产品上显示的'默认照片'
//缩略图(在产品索引处)
[必填]
public字符串ThumbnailImage {get;组; }

//此属性包含要在产品的
//详细信息页面上显示的所选照片
[必需]
public IEnumerable< string> SelectedImages {get;组; }

[必需]
public int Price {get;组; }

[必需]
public int ShippingCost {get;组; }

[必需]
public int NumberAvailable {get;组; }

//此字段包含数据库中所有可用的照片
public IEnumerable< SelectListItem> MultiSelectAvailableImages {get;组; }

public IEnumerable< SelectListItem> SelectListAvailableImages {get;组;

public NewProductViewModel(IEnumerable< string> availableImages)
{
this.MultiSelectAvailableImages = new MultiSelectList(availableImages);
this.SelectListAvailableImages = new SelectList(availableImages);
}

public NewProductViewModel()
{
}
}
}





查看:



 @model Mom_Website.ViewModels.NewProductViewModel 

@ {
ViewBag.Title =新;
}

< h2>新产品< / h2>

@using(Html.BeginForm(保存,产品))
{
< div class =form-group>
@ Html.LabelFor(m => m.Name)
@ Html.TextBoxFor(m => m.Name,new {@class =form-control})
@ Html.ValidationMessageFor(m => m.Name)
< / div>
< div class =form-group>
@ Html.LabelFor(m => m.Description)
@ Html.TextBoxFor(m => m.Description,new {@class =form-control})
@ Html.ValidationMessageFor(m => m.Description)
< / div>
< div class =form-group>
@ Html.LabelFor(m => m.NumberAvailable)
@ Html.TextBoxFor(m => m.NumberAvailable,new {@class =form-control})
@ Html.ValidationMessageFor(m => m.NumberAvailable)
< / div>
< div class =form-group>
@ Html.LabelFor(m => m.Price)
@ Html.TextBoxFor(m => m.Price,new {@class =form-control})
@ Html.ValidationMessageFor(m => m.Price)
< / div>
< div class =form-group>
@ Html.LabelFor(m => m.ShippingCost)
@ Html.TextBoxFor(m => m.ShippingCost,new {@class =form-control})
@ Html.ValidationMessageFor(m => m.ShippingCost)
< / div>
< div class =form-group>
@ Html.LabelFor(m => m.ThumbnailImage)
@ Html.DropDownListFor(m => m.ThumbnailImage,Model.SelectListAvailableImages,选择默认图片,新{@class = form-control})
@ Html.ValidationMessageFor(m => m.ThumbnailImage)
< / div>
< div class =form-group>
@ Html.LabelFor(m => m.SelectedImages)
@ Html.ListBoxFor(m => m.SelectedImages,Model.MultiSelectAvailableImages,new {@class =form-control})
@ Html.ValidationMessageFor(m => m.SelectedImages)
< / div>
@ Html.HiddenFor(m => m.Id)
@ Html.AntiForgeryToken()
< button type =submitclass =btn btn-primary> Save< ; /按钮>
}

@section scripts
{
@ Scripts.Render(〜/ Bundles / jqueryval)
}

解决方案

这是我们遇到的最常见问题之一,也是我们最不能回答的问题,但你最有能力回答自己。



让我解释一下错误的含义:你试图使用变量,属性或方法返回值,但它包含null - 这意味着它有变量中没有类的实例。

它有点像一个口袋:你的衬衫里有一个口袋,用来握笔。如果你进入口袋并发现那里没有笔,你就不能在一张纸上签名 - 如果你尝试的话,你会得到非常有趣的外观!空口袋给你一个空值(这里没有笔!)所以你不能做任何你检索笔通常做的事情。它为什么空?这就是问题 - 可能是你今天早上离开家时忘了拿起你的笔,或者你昨晚把它拿到昨天的衬衫口袋里时可能会把笔留下来。



我们无法分辨,因为我们不在那里,更重要的是,我们甚至看不到你的衬衫,更不用说口袋里的东西了!



回到计算机,你做了同样的事情,不知何故 - 我们看不到你的代码,更不用说运行它了,找不到包含null的东西。

但是你可以 - 而Visual Studio将在这里帮助你。在调试器中运行您的程序,当它失败时,VS将向您显示它发现问题的行。然后,您可以开始查看它的各个部分,以查看哪个值为null,并开始回顾代码以找出原因。因此,在包含错误行的方法的开头放置一个断点,然后从头再次运行程序。这一次,VS会在错误发生前停止,让你通过查看代码来查看你的价值来检查发生了什么。



但我们做不到那 - 我们没有您的代码,如果我们拥有它,我们不知道如何使用它,我们没有您的数据。所以试试吧 - 看看你能找到多少信息!


所以....经过大量的调试后,我必须说问题非常简单。 br />


首先,当您使用模型绑定时,不要以任何方式使用构造函数。它会破坏你的大脑。而是在控制器上创建ViewModel实例时设置值。例如:

 ViewModelClass myViewModel = new ViewModelClass(); 
myViewModel.ThePropertyIWantToSet = SomeData;



这是问题的根源。



其次,我错了保存控制器上的动作。我在那里提交数据后返回了一个View ...而没有传递ViewModel(当然)。我改变了这个:

 return View(New); 

to:



返回RedirectToAction(新); 





我希望此评论将来会帮助人们!!


Hello ! I am trying to implement a select list(DropDownListFor) and a Multi Select List(ListBoxFor) in ASP.NET(MVC5), and i am getting an 'Object reference not set to an instance of an object' exception when i submit the form. I found a bunch of stack overflow articles, that didn't actually helped me me much. I tried a lot of things, but no much of a luck.

Here is a photo of the exception: [Exception Photo,
click me!
]

What I have tried:

Controller:

public ActionResult New()
        {
            List<string> availableImages = new List<string>();
            //here i an getting the path for all the available images from 
            // the database
            foreach (Image contextImage in _context.Images)
            {
                availableImages.Add(contextImage.FullName);
            }
            
            return View("New", new NewProductViewModel(availableImages));
        }



ViewModel:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Mom_Website.Models;

namespace Mom_Website.ViewModels
{
    public class NewProductViewModel
    {
        public int Id { get; set; }

        [Required]
        [StringLength(40)]
        public string Name { get; set; }

        [Required]
        public string Description { get; set; }

        //This is the 'default photo' that will be displayed at the product
        //thumbnail(at the product's index)
        [Required]
        public string ThumbnailImage { get; set; }

        //This property contains the selected photos to be displayed on the
        //Details page of the product
        [Required]
        public IEnumerable<string> SelectedImages { get; set; }

        [Required]
        public int Price { get; set; }

        [Required]
        public int ShippingCost { get; set; }

        [Required]
        public int NumberAvailable { get; set; }

        //this field contains all the available photos on the database
        public IEnumerable<SelectListItem> MultiSelectAvailableImages { get; set; }

        public IEnumerable<SelectListItem> SelectListAvailableImages { get; set; }

        public NewProductViewModel(IEnumerable<string> availableImages)
        {
            this.MultiSelectAvailableImages = new MultiSelectList(availableImages);
            this.SelectListAvailableImages = new SelectList(availableImages);
        }

        public NewProductViewModel()
        {
        }
    }
}



View:

@model Mom_Website.ViewModels.NewProductViewModel

@{
    ViewBag.Title = "New";
}

<h2>New Product</h2>

@using (Html.BeginForm("Save", "Products"))
{
    <div class="form-group">
        @Html.LabelFor(m => m.Name)
        @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Name)
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Description)
        @Html.TextBoxFor(m => m.Description, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Description)
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.NumberAvailable)
        @Html.TextBoxFor(m => m.NumberAvailable, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.NumberAvailable)
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Price)
        @Html.TextBoxFor(m => m.Price, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.Price)
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ShippingCost)
        @Html.TextBoxFor(m => m.ShippingCost, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.ShippingCost)
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ThumbnailImage)
        @Html.DropDownListFor(m => m.ThumbnailImage, Model.SelectListAvailableImages, "Select Default Image", new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.ThumbnailImage)
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.SelectedImages)
        @Html.ListBoxFor(m => m.SelectedImages, Model.MultiSelectAvailableImages, new { @class = "form-control" })
        @Html.ValidationMessageFor(m => m.SelectedImages)
    </div>
    @Html.HiddenFor(m => m.Id)
    @Html.AntiForgeryToken()
    <button type="submit" class="btn btn-primary">Save</button>
}

@section scripts
{
    @Scripts.Render("~/Bundles/jqueryval")
}

解决方案

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!


So.... after a lot of debugging going on here, i must say that the problem was really simple.

First, DO NOT USE a constructor in ANY way when you use model binding. It will destroy your brain on the process. Instead, set the values when you create the instance of the ViewModel on the controller. For example:

ViewModelClass myViewModel = new ViewModelClass();
myViewModel.ThePropertyIWantToSet = SomeData;


This was the root of the problem.

Second, i was mistaken on the save action on the controller. I returned a View after submitting the data there... without passing a ViewModel(of course). I change this:

return View("New"); 

to:

return RedirectToAction("New");



I hope this comment will help people in the future !!


这篇关于选择列表和多选列表|你调用的对象是空的。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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