mvc 将带有模型的文件传递给控制器​​ post

mvc pass file with model to controller post

是否可以将 HttpPostedFileBase 连接到 post 上的模型到控制器?

没有模型我只能通过 HttpPostedFileBase

在我浏览器的网络选项卡中,我看到文件正在附加,但当它到达我的控制器时它是空的

[HttpPost]
public ActionResult ProcessFile(UploadMopdelWrapper model)
{

}

public class UploadMopdelWrapper
{
    public UploadMopdelWrapper()
    {

    }

    public UploadMopdelWrapper(UploadMopdel upload)
    {
        UploadModel = upload;
    }
    public HttpPostedFileBase SelectedFile { get; set; }
    public UploadMopdel UploadModel { get; set; }
    public IEnumerable<ExcelRecord> ExcelList { get; set; }
}

这里是景色

@using (@Html.BeginForm("ProcessFile", "Hcp", new { enctype = "multipart/form-data" }))
{
    <div class="form-group">
        <div class="col-md-4 text-right">
            @Html.LabelFor(x => x.UploadModel.JobNumber, new { @class = "control-label" })
        </div>
        <div class="col-md-8">
            @Html.TextBoxFor(x => x.UploadModel.JobNumber, new { @class = "form-control" })
            @Html.ValidationMessageFor(x=>x.UploadModel.JobNumber, null, new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-4 text-right">
            @Html.LabelFor(x => x.UploadModel.JobName, new { @class = "control-label" })
        </div>
        <div class="col-md-8">
            @Html.TextBoxFor(x => x.UploadModel.JobName, new { @class = "form-control" })
            @Html.ValidationMessageFor(x => x.UploadModel.JobName, null, new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-4 text-right">
            @Html.LabelFor(x => x.UploadModel.NotificationEmail, new { @class = "control-label" })
        </div>
        <div class="col-md-8">
            @Html.TextBoxFor(x => x.UploadModel.NotificationEmail, new { @class = "form-control" })
            @Html.ValidationMessageFor(x => x.UploadModel.NotificationEmail, null, new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-4 text-right">
            <label class="control-label">Selkect a File:</label>
        </div>
        <div class="col-md-8">
            <input type="file" name="selectedFile" />
        </div>
    </div>
    <div class="col-md-offset-4 col-md-8">
        <input type="submit" class="btn btn-info btn-block col-md-12" />
    </div>

}

在我的网络选项卡中,我看到了这个:

UploadModel.JobNumber:1
UploadModel.JobName:w
UploadModel.NotificationEmail:w
selectedFile:week7_homework.sql

你必须像

一样Post设置表单方法
@using (@Html.BeginForm("ProcessFile", "Hcp",FormMethod.Post, new { enctype = "multipart/form-data" }))

因为否则它会将 new { enctype = "multipart/form-data" } 视为路由值。如果您查看 BeginForm 的重载,您正在使用

FormExtensions.BeginForm 方法(HtmlHelper、字符串、字符串、对象)