Javascript 在ASP.NETMVC中使用Jquery上传表单数据和文件

Javascript 在ASP.NETMVC中使用Jquery上传表单数据和文件,javascript,c#,jquery,asp.net,asp.net-mvc,Javascript,C#,Jquery,Asp.net,Asp.net Mvc,我使用这样的代码来接收客户信息。 除了我的客户信息,我还必须上传一个文件 CSHTML文件 @using (Html.BeginForm("AddPersonInfo", "Management", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmAddPerson" })) { @Html.AntiForgeryToken() <div id="divControls" class="form inline

我使用这样的代码来接收客户信息。 除了我的客户信息,我还必须上传一个文件

CSHTML文件

@using (Html.BeginForm("AddPersonInfo", "Management", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmAddPerson" })) { @Html.AntiForgeryToken()
<div id="divControls" class="form inline">

    <div class="form-group">
        @Html.LabelFor(model => model.FName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-12">
            @Html.EditorFor(model => model.FName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.FName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.LName, htmlAttributes: new { @class = "control-label col-md-2"})
        <div class="col-md-12">
            @Html.EditorFor(model => model.LName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.LName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.FileName, htmlAttributes: new { @class = "control-label col-md-2", style = "float: right" })
        <div class="col-md-12">
            <input id="postedFile" type="file" data-buttonText="Select File">
            @Html.ValidationMessageFor(model => model.FileName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-12">
            <input style="float: right" id="btnSave" type="button" value="Save" class="btn btn-info" />
        </div>
    </div>
</div>
}

在控制器中的AddPersonInfo中,文件信息(postedFile)将被正确接收,但表单信息(模型)将被接收为空。在
ajax
请求中,您只需将
postedFile
添加到
FormData()

尝试手动添加模型

var formData = new FormData();
var file = document.getElementById("postedFile").files[0];
formData.append("postedFile", file);

var model: {
  'FName' : 'John',
  'LName' : 'Smith'
}
formData.append('model', model);
public ActionResult AddPersonInfo(PersonViewModel model, HttpPostedFileBase postedFile)
{
    try
    {
        //
    }
    catch
    {
        //
    }
}
var formData = new FormData();
var file = document.getElementById("postedFile").files[0];
formData.append("postedFile", file);
var formData = new FormData();
var file = document.getElementById("postedFile").files[0];
formData.append("postedFile", file);

var model: {
  'FName' : 'John',
  'LName' : 'Smith'
}
formData.append('model', model);