Почему HttpPostedFile становится пустым в методе действия из вида? - PullRequest
1 голос
/ 17 апреля 2019

Я пытаюсь загрузить файл, но при сохранении он выдает ошибку в действии, т. Е. Ссылка на объект не установлена, а также значение равно NULL.

Это тот же класс, который передается и сохраняется, но все равно он выбрасываетошибка.Почему это ноль?Он привязан к той же модели представления.

@model VAILCertificates.UI.ViewModels.AddInspectionReportViewModel

@using (Html.BeginForm("Create", "InspectionReport", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
     <div class="form-group">
          @Html.LabelFor(model => model.File, htmlAttributes: new { @class = "control-label col-md-2" })
          <div class="col-md-5">
               @Html.TextBoxFor(model => model.File, new { @class = "form-control", type = "file" })
               @Html.ValidationMessageFor(model => model.File, "", new { @class = "text-danger" })
          </div>
     </div>
     <button class="btn btn-success btn-outline btn-block" type="submit"><i class="fa fa-save" style="font-size:medium"></i>  Add</button>
}

Действие:

public ActionResult Create(AddInspectionReportViewModel model, HttpPostedFileBase FileName)   
    {
         string FilePath = Server.MapPath("~/Downloads/Certificates/");
                            model.File.SaveAs(FilePath + Path.GetFileName(model.File.FileName));
         model.InspectionReport.FileName = Path.GetFileName(model.File.FileName);

        InspectionReportDAL.AddInspectionReport(model.InspectionReport);
        return RedirectToAction("Index");
    }

Модель представления:

public class AddInspectionReportViewModel
{
     public HttpPostedFile File { get; set; }
     public InspectionReport InspectionReport { get; set; }
}

Класс:

public class InspectionReport
    {
        //General Details
        public int InspectionReportID { get; set; }


        public string FileName { get; set; }
    }

Обновление: внутренняя ошибка

The parameter conversion from type 'System.Web.HttpPostedFileWrapper' to type 'System.Web.HttpPostedFile' failed because no type converter can convert between these types.

Ответы [ 3 ]

1 голос
/ 17 апреля 2019

Измените viewModel на:

 public class AddInspectionReportViewModel
            {
                [DataType(DataType.Upload)]
                public HttpPostedFileBase File { get; set; }
                public InspectionReport InspectionReport { get; set; }
            }

измените представление на:

@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div class="form-group">
        @Html.LabelFor(model => model.File, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-5">
            @Html.TextBoxFor(m => m.File, new { type = "file" })
            @Html.ValidationMessageFor(model => model.File, "", new { @class = "text-danger" })
        </div>
    </div>
    <button class="btn btn-success btn-outline btn-block" type="submit"><i class="fa fa-save" style="font-size:medium"></i>  Add</button>
}
1 голос
/ 17 апреля 2019

HttpPostedFileBase FileName

model.File

Имя параметра, которого ожидает метод, - FileName.

Изменить это @Html.TextBoxFor(model => model.File, new { @class = "form-control", type = "file" })

на

@Html.TextBoxFor(model => model.File.FileName , new { @class = "form-control", type = "file" })

Основываясь на комментариях, я бы сделал следующее, если это возможно.

На вашем месте я удалил бы @Html.TextBoxFor(model => model.File, new { @class = "form-control", type = "file" }) и заменил бы его на:

<input type="file" name="FileName" id="fileUpload or whatever" accept="//Whatever file you want to accept">

В текущем состоянии вы никогда не передаете ничего параметру HttpPostedFileBase, только модель и, следовательно, она всегда равна нулю.

0 голосов
/ 17 апреля 2019

Изменение HttpPostedFile на HttpPostedFileBase сработало.

 public class AddInspectionReportViewModel
    {
        public HttpPostedFileBase File { get; set; }
        public InspectionReport InspectionReport { get; set; }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...