如何将带有fromdata的json对象发送到mvc控制器

时间:2019-01-19 10:45:17

标签: c# jquery asp.net-mvc model-binding

我正在将formdata数据对象发送到mvc控制器。我在控制器中收到数组,但是该对象始终丢失。经过大量搜索后仍未找到任何线索。

我尝试发送整个对象或将每个值附加到formdata,但它始终为null。 formdata接受吗?嵌套对象。

我的jQuery代码:

 function addstudent() {
       var form= $("#studentform").valid();
        if (form)
        {

            personfood.details.firstname = $("#firstname").val();
            personfood.details.lastname = $("#lastname").val();
            personfood.details.imageuploaded = $("#imageupload")[0].files[0];
            personfood.details.rememberme = $("#rememberme").is(":checked");
            personfood.details.newsletter = $("#newsletter").is(":checked");
            personfood.details.gender = $("input[name='gender']").val();

            var personfoods = new FormData();

            $.each(personfood.details, function (key, value) {
                personfoods.append(key, value);
            });
            $.each(personfood.foodname, function (key, value) {
                personfoods.append("foodname["+[key]+"]", value);

            });

            for (var pair of personfoods.entries()) {
                console.log(pair[0] + ', ' + pair[1]);
            }

            $.ajax({
                url: "/Main/addperson",
                type: "POST",
                processData: false,
                cache: false,
                contentType: false,
                dataType: "json",
                data: personfoods,
                success: onsucessinsert,
                error:onerrorinsert
            })

        }

我的ViewModel

 public class personfoods
 {
    public details details { get; set; }
    public List<string> foodname { get; set; }
 }

details模型:

public class details
{
    public int id { get; set; }
    public string firstname { get; set; }
    public string lastname { get; set; }
    public string imagename { get; set; }
    public string imageshorturl { get; set; }
    public string imagefullurl { get; set; }
    public bool rememberme {get;set;}
    public bool newsletter { get; set; } 
    public string gender { get; set;}
    public HttpPostedFileBase imageuploaded { get; set; }
} 

2 个答案:

答案 0 :(得分:0)

我使用$ .each解决此问题,并将键值对附加到我的formdata中。

$.each(personfood.details, function (key, value) {
                personfoods.append("details[" + key + "]",value);
            });

答案 1 :(得分:-1)

ContentType应该为''application / json; charset = utf-8”,您将无法像以前那样发布文件。我认为data:JSON.stringify(personfoods);应该可用于其余属性。