上传文件时,这两行代码似乎做同样的事情,但只有其中一行有效

时间:2018-04-27 02:48:29

标签: asp.net-mvc asp.net-mvc-5

我尝试在我的视图中编写以下两行来上传文件。

@using (Html.BeginForm(new { enctype = "multipart/form-data" })) 

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

POST操作符上的Create操作的代码行Attachments,两条线都显示我在Create内设置的断点。但是,只有第二行正确上传附件。第一行的附件设置为null

为什么第一行不上传文件,即使它似乎也在POST Create上执行了Attachments

查看:

@using (Html.BeginForm(new { enctype = "multipart/form-data" })) 
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Attachment</h4>

    <div class="form-group">
        @Html.LabelFor(model => model.File, htmlAttributes: new { @class = "control-label col-md-4" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.File, htmlAttributes: new { @class = "form-control", type = "file", name = "file"})
            @Html.ValidationMessageFor(model => model.File, "", new { @class = "text-danger" })
        </div>
    </div>


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

</div>
}

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "AttachmentID,AttachmentName")] Attachment attachment, HttpPostedFileBase file)
{
    if (ModelState.IsValid)
    {
        db.Attachments.Add(attachment);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(attachment);
}

1 个答案:

答案 0 :(得分:2)

要上传文件,<form>元素需要enctype = "multipart/form-data"属性。

您首次尝试使用this overload添加路由值,并假设GET方法是Create() AttachmentsController方法,您正在生成

<form action="/Attachments/Create?enctype=multipart/form-data" method="post">

并且没有enctype属性,因此HttpPostedFileBase file参数为null

第二次尝试使用this overload,其中第四个参数是htmlAttributes并生成

<form action="/Attachments/Create" method="post" enctype="multipart/form-data">