简体   繁体   中英

How to Send json object with fromdata to mvc controller

I am sending formdata data object to mvc controller. I received the array in controller but the object is always missing. Searched a lot about it did not find a clue.

I have tried to send whole object or appending each value to formdata but its always null. does formdata accepts? nested object.

My jQuery code:

 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
            })

        }

My ViewModel

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

details model:

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; }
} 

i solve it using $.each and appending key value pairs to my formdata.

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

ContentType should be ''application/json; charset=utf-8" and you can not post files like you are doing. I think data:JSON.stringify(personfoods); should work for remaining properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM