PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 8, 2022

[FIXED] How to pass an object to controller using ajax call

 September 08, 2022     ajax, asp.net-mvc, jquery     No comments   

Issue

I want to pass an object to controller and retrieve the values in the controller. I have defined like:

Html code:

 var positionarray = [];

Javascript:

 $("#button").live('click',function(){
     positionarray.push({
         id: sessionStorage.getItem('id'),
         value: $("#input").val() 
     });
 });

 // on save button click
 $.ajax({
       type: "GET",                                                 
       url:"/Bugs/Position",                                                 
       data: {
           array:positionarray      
       },
       cache: false,
       dataType: "json",
       contentType: "application/json; charset=utf-8",
       success: function (json) {

       }
 });

But i am not able to retrieve the values in the controller. It is getting null.


Solution

Try this:- You are passing an array of objects so you should do HTTPPost rather than HttpGet (this will work for array of primitive types say list of int, strgin etc) sending it through query string(Remember the limit for query string). Try this with HTTPPost

 $.ajax({
       type: "POST",                     
       url:"Home/Position",                                                 
       data: JSON.stringify({
              array: positionarray
       }),
       cache: false,
       dataType: "json",
       contentType: "application/json; charset=utf-8",
       success: function (json) {

       }

[HTTPPost]
public void Position(YourClass[] array){...


Answered By - PSL
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing