3

I'm new to MVC ASP.NET and C# altogether really, so apologies if I misunderstand some parts of what I'm trying to ask.

I am trying to upload a file to a location (on my own C: drive for the purposes of this test) and record information about the upload to a SQL table. To this end, I have an EDM based on a table called "InputFiles", and have followed a series of tutorials (including responses to 'Submitting two HTML forms with one submit button in Razor') to get to where I am now.

There's no functionality for most of this yet, but the idea is that the user picks one of 6 templates from a drop down in the form, and selects their file for upload, clicking one button that will record the upload date, the user's own information, the filename etc. and also upload the file to a location dictated by the template number the user selects.

I feel like I can tackle the issue of uploading to different locations dependent on the template selected. But upon checking that the file for upload has any content, I was getting the following error until I added the Null Check:

An exception of type 'System.NullReferenceException' occurred in Test2.dll but was not handled in user code Additional information: Object reference not set to an instance of an object.

"File" is seemingly always null, and hence the upload skipped altogether.

Extensive Googling hasn't yet helped me find some kind of meaningful fix, or tell me what heinous crime I've committed on the way to this point.

This is my controller with my Create method

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(InputFile inputFile)
    {
        if (ModelState.IsValid)
        {
            if (inputFile.File != null)
            if (inputFile.File.ContentLength > 0) 
            //this is where the error occurred when I clicked "create"
            {
                string _FileName = Path.GetFileName(inputFile.File.FileName);
                string _path = Path.Combine(@"C:\_Staging\ImportFiles\RotW\_Import", _FileName);
                inputFile.File.SaveAs(_path);
                inputFile.FileName = _FileName;
            }

            db.InputFiles.Add(inputFile);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.Template = new SelectList(db.Templates, "ID", "TemplateName", inputFile.Template);
        return View(inputFile);
    }

And my model:

public partial class InputFile
{
    [Key]
    public int ID { get; set; }
    public string FileName { get; set; } //this needs to be taken from _FileName variable

    private DateTime? uploadDate = null;
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime UploadDate
    {
        get { return uploadDate ?? DateTime.Now; }
        set { uploadDate = value; }
    }
    public int Template { get; set; }
    public int PeriodID { get; set; }

    public virtual Template Template1 { get; set; }

    [NotMapped]
    public HttpPostedFileBase File { get; set; }
}

EDIT - View:

    @model Test2.Models.InputFile

    @{
        ViewBag.Title = "Create";
    }

    <h2>Create</h2>


    @using (Html.BeginForm())
     {
         @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>InputFile</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    <div class="form-group">
        @Html.LabelFor(model => model.Template, "Template", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("Template", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Template, "", new { @class = "text-danger" })
        </div>
    </div>
    <div>
        <label>File</label>
        <input type="file" name="File" id="File" />
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>

}

Cheers

a92inv
  • 31
  • 2
  • You need to show your view code as well –  Jun 28 '18 at 21:56
  • 2
    Your form is not set up correctly to allow file uploads. `@using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))` As any HTML file upload tutorial will tell you, you need the enctype attribute on your form before any uploads will work. – ADyson Jun 29 '18 at 09:32

0 Answers0