【问题标题】:MVC || HTML Form || Object reference not set to an instance of an objectMVC || HTML 表单 ||你调用的对象是空的
【发布时间】:2014-05-29 17:58:55
【问题描述】:

我得到了这个错误,我不知道如何解决它:

“对象引用未设置为对象的实例。”

Line 48:         public ActionResult Upload(imageFile imageFile)
Line 49:         {
Line 50:             foreach (var image in imageFile.files)
Line 51:             {
Line 52:                 if (image.ContentLength > 0)

我尝试使用 ID 属性和 name 属性,但没有...

这是我的控制器中有问题的部分:

     [HttpPost]
    public ActionResult Upload(imageFile imageFile)
    {
        foreach (var image in imageFile.files)
        {
            if (image.ContentLength > 0)
            {
                CloudBlobContainer blobContainer = _blobStorageService.GetCloudBlobContainer();
                CloudBlockBlob blob = blobContainer.GetBlockBlobReference(image.FileName);
                blob.UploadFromStream(image.InputStream);
            }
        }
        return RedirectToAction("Upload");
    }

这是 HTML.Form :

<p>
    @using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <input type="file" name="imageFile" id="imageFile" multiple />
        <input type="submit" name="submit" value="Upload" />
    }
</p>

这是“imageFile”类:

public class imageFile
{
    public IEnumerable<HttpPostedFileBase> files { get; set; }
}

我做错了什么?我读了很多关于这个例外的帖子,但没有一个对我有帮助..

谢谢。

【问题讨论】:

  • 异常意味着您正在尝试使用一个对象 (imageFile) 但它为空。这可能是最常见的例外
  • 尝试将操作中的参数名称从 imageFile 更改为 file。有时绑定很挑剔。
  • @KyleGobel 是的,我明白了,你知道如何解决它吗?
  • @Josh 这个问题没有更传统的解决方案吗?

标签: html asp.net-mvc http-post forms


【解决方案1】:

只需将您的 html 输入的名称更改为 files,就像在您的模型类中一样:

视图中的输入元素:

<input type="file" name="files" id="files" multiple />

你的模型:

public class imageFile
{
    public IEnumerable<HttpPostedFileBase> files { get; set; }
}

【讨论】:

    猜你喜欢
    • 2014-08-26
    • 1970-01-01
    • 2013-05-27
    • 2013-07-22
    相关资源
    最近更新 更多