HttpPostedFileBase没有绑定到模型

时间:2019-08-14 10:07:13

标签: c# html asp.net-mvc httppostedfilebase

我正在尝试使用视图模型中包含的HttpPostedFileBase类上传图像。我的代码如下所示

@using(Html.BeginForm("EditUserProfilePartial", "UserProfile", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    <h3 class="text-center">@Model.Name</h3>
    <div class="w-100">
        <img class="mx-auto rounded-circle w-25 d-block" src="@Model.ProfilePicturePath" />
    </div>

    <div class="form-group">
        @Html.LabelFor(x => x.Name, Resources.UserProfileEditUserProfileUserName)
        @Html.TextBoxFor(x => x.Name, new { @class = "form-control", required = "true", placeholder = Resources.UserProfileEditUserProfileUserName })
    </div>
    <div class="form-group">
        @Html.LabelFor(x => x.Email, Resources.UserProfileEditUserProfileUserEmail)
        @Html.TextBoxFor(x => x.Email, new { @class = "form-control", required = "true", placeholder = Resources.UserProfileEditUserProfileUserEmail })
    </div>
    <div class="form-group">
        @Html.LabelFor(x => x.ProfilePicture, Resources.UserProfileEditUserProfileUserProfilePicture)
        <div class="custom-file">
            <input class="custom-file-input" type="file" name="@Html.NameFor(x => x.ProfilePicture)" id="@Html.IdFor(x => x.ProfilePicture)" placeholder="@Resources.UserProfileEditUserProfileUserProfilePicture" />
            @Html.LabelFor(x => x.ProfilePicture, Resources.UserProfileEditUserProfileUserProfilePicture, new { @class = "custom-file-label" })
        </div>
    </div>
}

和我的视图模型

public class EditUserProfileViewModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public HttpPostedFileBase ProfilePicture { get; set; }
    public string ProfilePicturePath { get; set; }
}

我已经在寻找解决方法,但是我发现的解决方案(大多是他们忘记添加enctype)对我不起作用。

编辑
我发现的结果和我认为非常有趣的是,当我通过在浏览器中输入网址直接调用操作时,文件上传就可以正常工作了。但是,当我通过使用ajax和jquery modal将表单作为模式附加到正文中时,它不是

1 个答案:

答案 0 :(得分:0)

当然不会。您没有将值绑定到任何东西。

将输入标签更新为类似的内容。

        <input class="custom-file-input" type="file" name="file" id="@Html.IdFor(x => x.ProfilePicture)" placeholder="@Resources.UserProfileEditUserProfileUserProfilePicture" accept=".png, .jpg, .jpeg" />

在这种情况下,您的控制器方法应类似于

EditUserProfilePartial(EditUserProfileViewModel model, HttpPostedFileBase file)