简体   繁体   中英

Send Multiple objects with Ajax to the ASP.NET MVC controller

I have one ViewModel that contains three Collection of ExternalProjectViewModel , CertificateUniverSityViewModel , CertificateInstitutionsViewModel .

CreateFreelancerProfileViewModel.cs

public class CreateFreelancerProfileViewModel : BaseViewModel
{
    // More ...
   public List<ExternalProjectViewModel> ExternalProjects { get; set; }   

   public List<CertificateUniverSityViewModel> CertificateUniverSitys { get; set; }

   public List<CertificateInstitutionsViewModel> CertificateInstitutions { get; set; }

}

My Ajax code:

            $('#Controller').on('click','#SaveProfile',

            function() {

                debugger;
                var CertificateInstitutions = 
                    JSON.parse(localStorage.getItem("CertificateInstitutionsListLocal"));

                var CertificateUniverSitys = 
                    JSON.parse(localStorage.getItem("CertificateUniverSitysListLocal"));

                var ExternalProjects = 
                    JSON.parse(localStorage.getItem("ExProjectListLocal"));

                $.ajax({
                    url : '@Url.Action(MVC.Freelancer.Profile.CreatePrfile())',
                    method: "POST",
                    data: {
                        ExternalProjects,
                        CertificateUniverSitys,
                        CertificateInstitutions
                    }
                });


            });

When I Want Send Objects to Controller, First Get It from LocalStorage And After Get it Send it to Controller Action:

 public virtual ActionResult CreatePrfile(CreateFreelancerProfileViewModel viewModel)

When I see viewModel Values Show My Objects Count That is 2 but Objects Properties is null.so that my server object properties name equally with the client Object properties name.

LocalStorage Values

[{"ExternalProjects":{"Name":"wqeqwe","Body":"wqewqe","Url":‌​"wqewqe"}}]

[{"CertificateUniverSity":{"Name":"sad","Description":"sadas‌​","DateOfGets":"sad"‌​,"CertificateType":"‌​2","Field":"sadasd",‌​"UniName":"sad","Cer‌​tificateUniverSityLe‌​vel":"2"}}]

You could send them as JSON payload:

$.ajax({
    url : '@Url.Action(MVC.Freelancer.Profile.CreatePrfile())',
    method: 'POST',
    contentType: 'application/json',
    data: JSON.stringify({
        externalProjects: ExternalProjects,
        certificateUniverSitys: CertificateUniverSitys,
        certificateInstitutions: CertificateInstitutions
    }),
    success: function(result) {
        alert('data sent successfully');
    }
});

This assumes that the instances you got from the localStorage of those 3 variables represent javascript arrays with the corresponding objects in it.

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