使用Ajax.Beginform发送multipart / form-data

时间:2015-08-16 17:27:30

标签: ajax asp.net-mvc

我正在尝试在我的视图中将多部分/表单数据发布到Web API。视图的代码是:

<uc:UseCasePropertyDisplay Label="Name" Text="{Binding SelectedUseCase.Name, Mode=TwoWay}" />

我在beginform helper方法和ajax调用中的http属性中将内容类型设置为multipart / form-data。但是,在我的api方法中,我得到了例外说法:

@{
ViewBag.Title = "Upload";
}

<h2>Upload Image</h2>

<div>
@using (Ajax.BeginForm(null, null, null, new AjaxOptions { HttpMethod = "Post", Url = "http://localhost:59650/api/ingestion/upload", OnSuccess = "OnSuccess", OnFailure = "OnFailure", OnBegin = "OnBegin" }, new { enctype = "multipart/form-data" }))
{
    <div>
        <ol>
            <li>
                <input type="file" name="FileUpload" />
            </li>

            <li>
                @Html.Label("SheetName: ")
                @Html.TextBox("SheetName")
            </li>

            <li>
                @Html.Label("Columns: ")
                @Html.TextBox("Columns")
            </li>

            <li>
                @Html.Label("File Name: ")
                @Html.TextBox("FileName", ViewData["FileName"])
            </li>
        </ol>
    </div>

    <div>
        <input type="submit" name="upload_btn" value="Upload" />
    </div>
}
</div>

@section Scripts
{
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script type="text/javascript">
        function OnBegin(xhr) {
            xhr.setRequestHeader("Content-Type", "multipart/form-data")
        }

        function OnSuccess(response) {
            alert("Upload Successfully");
            //TODO:change the location
            window.location.href = "http://localhost:59650/";
        }

        function OnFailure(response) {
            alert("Upload failed, Please try again");
            //TODO:change the location
            window.location.href = "http://localhost:59650/Ingestion/Uploading";
        }

    </script>
}

我在控制器中的Web API:

"Invalid 'HttpContent' instance provided. It does not have a 'multipart' content-type header with a 'boundary' parameter.\r\nParameter name: content"

我很困惑为什么我得到这个例外。有没有其他方法将表单发送到特定的URL并相应地处理响应而不是使用ajax.beginform方法?

0 个答案:

没有答案