【问题标题】:File input sending null to controller [duplicate]向控制器发送空值的文件输入[重复]
【发布时间】:2021-01-23 06:42:23
【问题描述】:

我在表单中有一个文件输入。理想情况下,我希望它允许在提交表单时上传多个文件。它发送的是空列表,所以我尝试更改为只接收一个文件,现在它发送的是空列表。

我的cshtml表单:

    @using (Html.BeginForm(nameof(ServiceCallController.AddMessage), "ServiceCall", FormMethod.Post))
    {
        @Html.HiddenFor(m => m.Id)
        <div class="row">
            <div class="col-md-1">
                @Html.Label("New Message")
            </div>
            <div class="col-md-11">
                @Html.Kendo().EditorFor(m => m.NewMessage).Tools(t => t.Clear())
            </div>
        </div>
        <div class="row">
            <div class="col-md-1">
                @Html.Label("Attachments")
            </div>
            <div class="col-md-11">
                <input type="file"
                       id="myFile"
                       name="myFile"
                />
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                @Html.Kendo().Button().Content("Add Message").Name("SubmitAddMessage")
            </div>
        </div>
    }

我的控制器方法:

    public ActionResult AddMessage(int id, string newMessage, HttpPostedFileBase myFile)
    {
        if (myFile == null) throw new ArgumentNullException(nameof(myFile));//This should not happen
        return RedirectToAction(nameof(MyView), new { id });
    }

以及网络标签请求表单数据中正在发送的内容:

Id: 5473
NewMessage: Why is this not working?
myFile: Chrysanthemum.jpg

我做错了什么?为什么我的文件没有发送到控制器?

【问题讨论】:

  • @devNull 是的。写这篇文章时,我没有在建议的问题列表中看到这一点。

标签: c# html forms file razor


【解决方案1】:

您应该将 enctype 添加为multipart/form-data

@using (Html.BeginForm(nameof(ServiceCallController.AddMessage), "ServiceCall", FormMethod.Post, new { enctype = "multipart/form-data" }))

以及动作方法:

[HttpPost]
public ActionResult AddMessage(int id, string newMessage, HttpPostedFileBase myFile)
{
    if (myFile == null) throw new ArgumentNullException(nameof(myFile));//This should not happen
    return RedirectToAction(nameof(MyView), new { id });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多