首页 > 解决方案 > 我有一个带有 httppostedfile 的表单,我想通过 jquery 提交。httppostedfile 提交值为空

问题描述

这是我的 html 代码,其中我有一个表单从用户那里获取一些输入,并且用户上传了一个文件:

<div class="modal fade" id="CreateCompanyModal">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <h2 class="modal-title">Create Company</h2>
        </div>
        <div class="modal-body">
            <form id="CreateCompanyForm">
                <label>New Company Name</label>
                @Html.TextBoxFor(m => m.CreateCompany.Name, new { @class = "form-control" })

                <label>Choose File:</label>
                <input type="file" id="userFile" name="userFile" /><br />
            </form>
        </div>
        <div class="modal-footer">
            <div class="btn-group">
                <a href="#" id="btnSaveToCreateCompany" class="btn btn-primary">Confirm</a>
            </div>
        </div>
    </div>
</div>

我在其中序列化表单并将其发送到控制器的 jquery 代码:

$("#btnSaveToCreateCompany").click(function () {
            var MyCreateCompanyForm = $("#CreateCompanyForm").serialize();

            $.ajax({
                type: "POST",
                url: "/Company/CreateNewcompany1",
                data: MyCreateCompanyForm,
                success: function (res) {
                    console.log(res);
                }
            })
        });

我的控制器功能,我在其中接收表单并实现其背后的逻辑:

    [HttpPost]
    public ActionResult CreateNewCompany1(HttpPostedFileBase postedFile, ListCreateEditDeleteCompaniesViewModel viewModel)
    {
        if (ModelState.IsValid)
        {
            string filePath = "";
            filePath = Server.MapPath("~/Images/");

            if (postedFile == null)
                postedFile = Request.Files["userFile"];

            if (!Directory.Exists(filePath))
                Directory.CreateDirectory(filePath);

            filePath = filePath + Path.GetFileName(postedFile.FileName);
            if (!System.IO.File.Exists(filePath))
            {
                postedFile.SaveAs(filePath);
            }
            else
                return RedirectToAction("FileExistsView", "Folder");
            string extention = Path.GetExtension(filePath);
            if (extention != ".png")
                return Json("extention is not png", JsonRequestBehavior.AllowGet);
            return Json(true, JsonRequestBehavior.AllowGet);
        }
        else
            return Json("invalid model", JsonRequestBehavior.AllowGet);
    }

标签: c#jqueryasp.netmodel-view-controllerasp.net-ajax

解决方案


推荐阅读