HttpPostedFileBase始终返回null

时间:2017-04-26 16:08:26

标签: asp.net asp.net-mvc file file-upload upload

我不知道为什么我的InvoicePDF总是为空。

型号:

public class CreateEventViewModel
{
    // [FileExtensions(Extensions = "pdf", ErrorMessage = "Akceptuję tylko pliki PDF")]
    public HttpPostedFileBase InvoicePDF { get; set; }
    ...
}

我还在web.config中添加了maxRequestLength="65536"但它没有帮助。

<form id="f">
    @using (Html.BeginForm("Create", "Event", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        <div>
            @Html.TextBoxFor(model => model.InvoicePDF, new { type = "file" })
            @*@Html.ValidationMessageFor(model => model.InvoicePDF)*@
        </div>
        ...
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <button type="button" class="btn btn-default" onclick="CountPrice()">Oblicz cenę</button>
                    <input type="submit" value="Zapisz" class="btn btn-default" />
                    <button type="button" id="cancel" class="btn btn-default">Wyjdź</button>
                </div>
            </div>
        </div>
    }
</form>

控制器操作:

[HttpPost]
public async Task<ActionResult> Create(CreateEventViewModel ev)
{
  ...
}

我在方法start处设置断点,ev.InvoicePDF始终为null。 问题在哪里?

1 个答案:

答案 0 :(得分:2)

删除表单标记。做一个观察源。这将有效:

@model Testy20161006.Controllers.CreateEventViewModel
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index53</title>
</head>
<body>
    <div>
        @*  remove this <form id="f">*@  
            @using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
                @Html.AntiForgeryToken()
                <div>
                    @Html.TextBoxFor(model => model.InvoicePDF, new { type = "file" })
                    @*@Html.ValidationMessageFor(model => model.InvoicePDF)*@
                </div>

                <div class="form-group">
                    <div class="col-md-offset-2 col-md-10">
                        <button type="button" class="btn btn-default" onclick="CountPrice()">Oblicz cenę</button>
                        <input type="submit" value="Zapisz" class="btn btn-default" />
                        <button type="button" id="cancel" class="btn btn-default">Wyjdź</button>
                    </div>
                </div>
            }
        @*</form>*@
    </div>
</body>
</html>

public class HomeController : Controller
{
    [HttpPost]
    public async Task<ActionResult> Create(CreateEventViewModel ev)
    {
        return View();
    }

    public ActionResult Index53()
    {
        CreateEventViewModel createEventViewModel = new CreateEventViewModel();
        return View(createEventViewModel);
    }