Pass list of object from view to controller via jquery ajax

asked 2022-06-03T00:00:06.1+00:00
zola 1 Reputation point

First I create a view model like this below

public class policyDetailsViewModel
{

    public class Rootobject
    {
        public int message_code { get; set; }
        public Data data { get; set; }
    }

    public class Data
    {
        public List<Mypolicydetail> myPolicyDetails { get; set; }
        public List<Proposerdetail> proposerDetails { get; set; }
    }

    public class Mypolicydetail
    {
        public Nullable<long> polCode { get; set; }
        public string polMaturityDate { get; set; }
    }

    public class Proposerdetail
    {
        public Nullable<long> prpCode { get; set; }
        public Nullable<long> clntCode { get; set; }
    }
}

Also, I have created my view as below

@model List<policyDetailsViewModel.Rootobject>

@if (Model != null){

@for (int i = 0; i < Model.Count; i++)
{    
   List<policyDetailsViewModel.Mypolicydetail> p_detail = Model[i].data.myPolicyDetails;
   for (int j = 0; j < p_detail.Count; j++)
     {

      <button class="btn btn-primary s" id="@p_detail[j].polCode" data-pdetail="@p_detail">Test @p_detail[j].polCode  </button>
}
}
}

<script type="text/javascript">
$(document).ready(function () {

    $(document).on("click", ".btn.btn-primary.s", function (ev) {
        ev.preventDefault();
        var p = $(this).attr('data-pdetail');

        $.ajax({
            //contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: "POST",
            url: '/client/policySummaryPreview',
            data: { "vm": p },
            success: function (res) {
                psummodal.find("#prv1").empty();
                psummodal.find("#prv1").html(res);
            },
            error: function (xhr) {
                //alert('errorLoad');
            }
        });

    });
});

</script>

Finally my controller looks like this

[HttpPost]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult policySummaryPreview(List<policyDetailsViewModel.Mypolicydetail> vm)
    {
        try
        {

            return PartialView("_partialPolicySummary");
        }
        catch (Exception ex)
        {

        }
        return null;
    }

My challenge is the List<policyDetailsViewModel.Mypolicydetail> vm is coming out null.
Any help would be appreciated.

Thank you

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
2,523 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
1,173 questions
No comments
{count} votes

1 answer

Sort by: Most helpful
  1. answered 2022-06-03T06:34:19.563+00:00
    Brando Zhang-MSFT 1,916 Reputation points Microsoft Employee

    Hi @zola ,

    According to your description, I found you directly use data-pdetail="@p_detail inside the view codes. This will not set the value inside the data-pdetail attribute instead of the type name.

    To solve this issue, I suggest you could try to use @JsonSerializer.Serialize(p_detail) to solve this issue.

    More details, you could refer to below codes:

    <div class="text-center">  
        <h1 class="display-4">Welcome</h1>  
        <p>Learn about <a href="https://learn.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>  
    </div>  
     @if (Model != null){  
          
     @for (int i = 0; i < Model.Count; i++)  
     {      
        List<CoreFiveMVC.Controllers.policyDetailsViewModel.Mypolicydetail> p_detail = Model[i].data.myPolicyDetails;  
        for (int j = 0; j < p_detail.Count; j++)  
          {  
               
           <button class="btn btn-primary s" id="@p_detail[j].polCode" data-pdetail="@JsonSerializer.Serialize(p_detail)">Test @p_detail[j].polCode  </button>  
     }  
     }  
     }  
    

    Then inside the backend , if you are using the asp.net core , you should add FromBody to accept the Json format.

    More details, you could refer to below codes:

             public ActionResult policySummaryPreview([FromBody]List<policyDetailsViewModel.Mypolicydetail> vm)  
    

    Result:

    1Jyk6.png

    No comments