1

I have a controller with three argument: two are HttpPostedFileBase file and IEnumerable<HttpPostedFileBase> files, and also I have a form with two input files, single and multiple. But I have a problem when I submit my form to the controller. I've got object reference not set to an instance of an object error. But when I just have a HttpPostedFileBase file I don't have any problems.

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ProductId,Name,ImageName,LargeImageName,EnglishName,Price,ShortDescription,Keyword,PageVisit,Status,CategoryId")] Good good, HttpPostedFileBase file, IEnumerable<HttpPostedFileBase> files)
    {
        if (ModelState.IsValid)
        {
            if (file.ContentLength > 0)
            {
                var versions = new Dictionary<string, string>();

                var path = Server.MapPath("/UploadFiles/Images/GoodGallery/");
                versions.Add("_small", "maxwidth=270&maxheight=180&format=jpg");
                versions.Add("_large", "maxwidth=600&maxheight=400&format=jpg");
                foreach (var suffix in versions.Keys)
                {
                    file.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                    ImageBuilder.Current.Build(new ImageJob(file.InputStream, path + file.FileName + suffix, new Instructions(versions[suffix]), false, true));
                }


                //good. = DateTime.Now.ToString();
                var dotPosition = file.FileName.IndexOf('.');
                var largeFileName = file.FileName.Insert(dotPosition, ".jpg_large");
                var fileName = file.FileName.Insert(dotPosition, ".jpg_small");
                good.LargeImageName = largeFileName;
                good.ImageName = fileName;

            }

            foreach (var file2 in files)
            {
                var versions = new Dictionary<string, string>();

                var path = Server.MapPath("/UploadFiles/Images/GoodGallery/");
                versions.Add("_small", "maxwidth=270&maxheight=180&format=jpg");
                versions.Add("_large", "maxwidth=600&maxheight=400&format=jpg");
                foreach (var suffix in versions.Keys)
                {
                    file2.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                    ImageBuilder.Current.Build(new ImageJob(file2.InputStream, path + file2.FileName + suffix, new Instructions(versions[suffix]), false, true));
                }



                var dotPosition = file2.FileName.IndexOf('.');
                var largeFileName = file2.FileName.Insert(dotPosition, ".jpg_large");
                var smallfileName = file2.FileName.Insert(dotPosition, ".jpg_small");
                good.Images.Add(new ImageList { LargeImageName = largeFileName, SmallImageName = smallfileName });

            }

            ViewBag.Message = "فایل با موفقیت آپلود شد.";


            //return RedirectToAction("Index");
        }

        db.Goods.Add(good);
        db.SaveChanges();

        ViewBag.CategoryId = new SelectList(db.Categories, "Id", "CategoryName", good.CategoryId);
        return View(good);

    }




    @using (Html.BeginForm("Create", "Good", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()


<div class="row">
    <div class="col-lg-12">
        <div class="card card-outline-info">
            <div class="card-header">
                <h4 class="m-b-0 text-white">فرم محصول</h4>
            </div>
            <div class="card-body">
                @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                <div class="form-body">
                    <h3 class="box-title">ایجاد محصول</h3>
                    <hr class="m-t-0 m-b-40">
                    <div class="row">

                <div class="form-horizontal">
                    <h3 class="box-title">آپلود تصویر</h3>
                    <hr class="m-t-0 m-b-40">

                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">

                                <form action="#" class="dropzone">
                                    <div class="fallback">
                                        <input name="file" type="file" />
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                    <h3 class="box-title">آپلود تصاویر اسلایدر</h3>
                    <hr class="m-t-0 m-b-40">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body">

                                <form action="#" class="dropzone">
                                    <div class="fallback">
                                        <input name="files" type="file" multiple/>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>

                    <hr>
                    <div class="form-actions">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="row">
                                    <div class="col-md-offset-3 col-md-9">
                                        <button type="submit" class="btn btn-success btn-lg">ثبت</button>
                                        <button type="button" class="btn btn-inverse btn-lg">بازگشت</button>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6"> </div>
                        </div>


                    </div>
                </div>
            </div>
            <!--/row-->

}

alex
  • 11
  • 2
  • You need to check if the `file2` is not `null` and the `ContentLength` is greater that `0` in your `foreach` loop - `if (file2 != null && file2.ContentLength > 0) { ...` –  Nov 13 '17 at 10:45
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Camilo Terevinto Nov 13 '17 at 10:48
  • @StephenMuecke , but I want to know why I got null value in `IEnumerable files` – alex Nov 13 '17 at 10:57
  • I assume that is because you did not select any files in the multiple input. I'll see if I can find you a link which explains it in detail –  Nov 13 '17 at 11:03
  • Have a look at the articles [here](https://www.mikesdotnetting.com/article/287/uploading-multiple-files-with-asp-net-mvc) and [here](http://michaelsync.net/2014/04/29/asp-net-mvc-multiple-files-upload-bug-or-by-design-issue) –  Nov 13 '17 at 11:09

0 Answers0