javascript - 将对象和文件从 ajax 非法调用传递到 Web Api 2 Controller

标签 javascript c# jquery ajax asp.net-web-api2

                           $.ajax({
                                url: `/api/issues/${ViewModels.issueViewModel.id}`,
                                method: "PUT",
                                data: {dto: ViewModels.issueViewModel, emailAttach: attachFileData},
                                headers: {
                                    'Authorization': 'Bearer ' + token
                                }
                            })

issueViewModel 是一个键值对对象,emailAttach 将是附加到 FormData 的文件 webapi2 Controller

 public IHttpActionResult CreateIssue(IssueDto dto, List<HttpFileCollectionBase> emailAttach)
    {
        //Some logic to handle objects passed
    }

IssueDto 看起来像这样

public int Id { get; set; }
    public string Description { get; set; }
    public string Note { get; set; }

    public List<int> PersonId { get; set; } //Extra 
    public List<string> ApplicationName { get; set; }
    public List<string> AttachedFiles { get; set; }

    public List<PslApplicationDto> PslApplicationDto { get; set; }
    public UrgencyFlag UrgencyFlag { get; set; }
    public CompletionFlag CompletionFlag { get; set; }

    public DateTime? CompletionDate { get; set; }
    public DateTime? DateIssueRegistered { get; set; }
    public DateTime? LastUpdate { get; set; }
    public int CompletionDuration { get; set; }

    public SolutionDto SolutionDto { get; set; }
    public PsUserDto PsUser{ get; set; }
    public EmailDto EmailDto { get; set; }
    public IssueCategorieDto Category { get; set; }
    public List<PersonDto> PersonDtos { get; set; }
    public List<IssueTagsDto> IssueTags { get; set; }
    public List<int> IssueTagsId { get; set; } // Extra info

    public int CategorieId { get; set; }
    public int PsUserId { get; set; }

所有这些信息都绑定(bind)到 ViewModel 并传递给 Controller emailAttach 是从这段代码生成的键值 FormData

function attachFile(e) {
e.stopImmediatePropagation();
e.preventDefault();

var attachmentInput = document.getElementById("attachInput");

if (typeof (attachmentInput.files[0]) === "undefined") {
    return toastr.error("Please select a file to attach");
}


attachFileData.append(attachmentInput.files[0].name, attachmentInput.files[0]);
appendAttachmentToForm(attachmentInput.files[0]);

最佳答案

尝试将IssueDto类中dto和文件的数据类型改为string。

关于javascript - 将对象和文件从 ajax 非法调用传递到 Web Api 2 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43364211/

相关文章:

c# - Catch(Exception) 和 Catch(Exception ex) 的区别

javascript - 使用 jQuery Buttonset 进行不需要的滚动

javascript - 使用 ionic、Angular 和 django+rest 框架上传图像

javascript - 如果折叠菜单打开,如何将 "class"添加到 "body"?

javascript - 使用 jQuery 使禁用按钮看起来禁用的最简单方法

c# - 使用默认参数的 DLLImport c++ 函数

c# - 添加附加参数时无法连接到 ASP.NET Web API

javascript - JQuery/Javascript 选择不可见元素

javascript - 每 15 秒制作一个充满的酒吧

javascript - 将 jQuery 用于 Dom 大纲。