我可以接受 HttpPostedFileBase 作为 ViewModel 的一部分吗

Can I accept a HttpPostedFileBase as part of a ViewModel

我正在设置一个视图和 ViewModel 来接受一些数据和一个文件。但是当我查看返回的模型时,我没有看到文件。

这是我的视图模型:

public class ResourceReviewViewModel
{
    public Guid ResourceReviewId { get; set; }
    //....
    [Display(Name="Review Document File")]
    public HttpPostedFileBase ReviewFile { get; set; }
}

我的看法:

我的控制器处理提交:

[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult ResourceReview(ResourceReviewViewModel model)
{
    //...
    return View(model); // model.ReviewFile is null
}

@model PublicationSystem.ViewModels.ResourceReviewViewModel

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

    <div class="form-horizontal">
        <h4>Submit Your Review</h4>
        <hr/>
        @Html.HiddenFor(model => model.RequestReviewId, new { htmlAttributes = new { @class = "form-control" } })

        <div class="form-group">
            @Html.LabelFor(model => model.ReviewFile, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <input type="file" id="ReviewFile" name="ReviewFile" value="ActionHandlerForForm" />
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Submit" class="btn btn-default" />
            </div>
        </div>
    </div>
}

模型返回值,但文件 属性 为 NULL。我从另一页复制的输入 HTML,所以我不确定我是否需要 value="ActionHandlerForForm"

是的,这是可能的。我认为在您的示例中您只是缺少 multipart/form-data

试试这个(将 "Index" 和 "Home" 替换为您拥有的 View/Controller:

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