如何通过AJAX将文件和表单数据一起发送到MVC?

时间:2017-10-30 09:10:48

标签: javascript ajax asp.net-mvc

我尝试将表单数据和(可选)文件从Javascript发送到ASP.NET MVC WebAPI控制器。发送数据按以下方式准备:

var save = function(){

    if (!validate())
        return;

    var details = new RecipeDetails();
    details.id = recipeDetails.id;
    details.name = name();
    details.description = description() !== "" ? description() : null;
    details.preparationTime = preparationTime();
    details.totalTime = totalTime();
    details.portions = portions() !== "" ? portions() : null;

    var formData = new FormData();
    formData.append("id", details.id);
    formData.append("name", details.name);
    formData.append("description", details.description);
    formData.append("preparationTime", details.preparationTime);
    formData.append("totalTime", details.totalTime);
    formData.append("portions", details.portions);

    recipeService.updateRecipeDetails(formData, saveSucceeded, saveFailed);

    spinnerVisible(true);
};

我还没有发送图片。服务以下列方式发送数据:

var postFormData = function (url, formData, success, failure) {

    $.ajax({
        type: "POST",
        url: url,
        contentType: false,
        data: formData,
        cache: false,
        processData: false,
        success: success,
        error: failure
    });
};

看起来Javascript正确发送数据,请求有效负载如下所示:

------WebKitFormBoundaryo4APLG1O4LUg7fSf
Content-Disposition: form-data; name="id"

1
------WebKitFormBoundaryo4APLG1O4LUg7fSf
Content-Disposition: form-data; name="name"

Naleśniki1
------WebKitFormBoundaryo4APLG1O4LUg7fSf
Content-Disposition: form-data; name="description"

Opis
------WebKitFormBoundaryo4APLG1O4LUg7fSf
Content-Disposition: form-data; name="preparationTime"

00:15:00
------WebKitFormBoundaryo4APLG1O4LUg7fSf
Content-Disposition: form-data; name="totalTime"

00:20:00
------WebKitFormBoundaryo4APLG1O4LUg7fSf
Content-Disposition: form-data; name="portions"

4
------WebKitFormBoundaryo4APLG1O4LUg7fSf--

控制器的操作如下所示:

    [HttpPost]
    [Authorize]
    public HttpResponseMessage UpdateRecipeDetails(RecipeDetailsDto details)
    {
        int userId = User.Identity.GetId();

        recipeService.UpdateRecipeDetails(userId, details);

        return Request.CreateResponse(details);
    }

现在的问题是,Javascript收到500错误,控件永远不会进入UpdateRecipeDetails方法。

现在澄清一下:

  • 我是第一次通过POST主体发送表单,一切正常,所以反序列化JSON似乎不是问题;
  • 我查看了IIS Express日志中的线索,但没有;
  • VS
  • 中的“输出/调试”窗格中没有任何内容

为什么我不能通过FormData发送表单数据?

回复标题:

Request URL:http://localhost:6868/api/RecipeBackend/UpdateRecipeDetails
Request Method:POST
Status Code:500 Internal Server Error
Remote Address:[::1]:6868
Referrer Policy:no-referrer-when-downgrade

Cache-Control:no-cache
Content-Length:0
Date:Mon, 30 Oct 2017 10:47:36 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=(...)=

0 个答案:

没有答案