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

本文关键字:一部分 ViewModel 作为 HttpPostedFileBase 我可以 | 更新日期: 2023-09-27 18:20:12

我正在设置一个视图和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"

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

是的,这是可能的。我认为在你的例子中,你只是错过了multipart/form-data

试试这个(将"索引"answers"主页"替换为您拥有的视图/控制器):

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