HttpPostedFileBase не привязывается к модели - программирование
Подтвердить что ты не робот

HttpPostedFileBase не привязывается к модели

вот мой ViewModel

public class FaultTypeViewModel
{
    [HiddenInput(DisplayValue = false)]
    public int TypeID { get; set; }

    [Required(ErrorMessageResourceType = typeof(AdministrationStrings), ErrorMessageResourceName = "FaultTypeNameRequired")]
    [Display(ResourceType = typeof(AdministrationStrings), Name = "FaultTypeName")]
    public string TypeName { get; set; }

    [Display(ResourceType = typeof(AdministrationStrings), Name = "FaultTypeDescription")]
    [DataType(DataType.MultilineText)]
    public string TypeDescription { get; set; }

    [Display(ResourceType = typeof(AdministrationStrings), Name = "FaultTypeImageFile")]
    public HttpPostedFileBase TypeImageFile { get; set; }

    [HiddenInput(DisplayValue = false)]
    public string TypeImageURL { get; set; }
}

Обратите внимание: у меня есть "TypeImageFile" HttpPostedFileBase Я бы ожидал, что связующее устройство будет связывать это свойство от формы с моделью, переходит к контроллеру bu. Я просто получаю нуль.

вот соответствующий код в представлении:

@using (Html.BeginForm("AddFaultType","Administration", FormMethod.Post))
{

    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            ×</button>
        <h3 id="myModalLabel">@SharedStrings.Add @SharedStrings.FaultType</h3>
    </div>
    <div class="modal-body">
        @Html.ValidationSummary(true)
        <div class="editor-label">
            @Html.LabelFor(model => model.TypeName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.TypeName)
            @Html.ValidationMessageFor(model => model.TypeName)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.TypeDescription)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.TypeDescription)
            @Html.ValidationMessageFor(model => model.TypeDescription)
        </div>
        <div class="editor-label">
            @Html.LabelFor(model => model.TypeImageFile)
        </div>
        <div class="editor-field">
            <input type="file" name="TypeImageFile" id="TypeImageFile" />
        </div>
    </div>

    <div class="modal-footer">
        <input type="submit" value="@SharedStrings.Add" class="btn btn-primary" />
        @Html.ActionLink(SharedStrings.Cancel, "Index", "Administration", null, new { Class = "btn", data_dismiss = "modal", aria_hidden = "true" })
    </div>
}

и вот контроллер:

        [HttpPost]
        public ActionResult AddFaultType(FaultTypeViewModel i_FaultToAdd)
        {
            var fileName = Path.GetFileName(i_FaultToAdd.TypeImageFile.FileName);
            var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
            i_FaultToAdd.TypeImageFile.SaveAs(path);

            return RedirectToAction("Index");
        }
4b9b3361

Ответ 1

Убедитесь, что вы установили атрибут enctype в своей форме multipart/form-data в своей форме, если хотите иметь возможность загружать файлы:

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

Ответ 2

Завершение ответа Дарина: Убедитесь, что вы установили атрибут enctype в форме для multipart/form-data в форме, если хотите иметь возможность загружать файлы:

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

Чтобы убедиться, что ваш <input> передается на контроллер как часть модели, используйте Html Helpers для Id и name как показано ниже:

<input type="file" id="@Html.IdFor(x=>x.HttpPostedFileBase)" name="@Html.NameFor(x=>x.HttpPostedFileBase)" accept=".csv,.txt"/>

Работает в MVC5 извините, я не могу найти ссылку на какие помощники доступны в MVC3