skip to Main Content

I’m trying to make a simple post call in a controller method using an ajax call from a razor view.The ajax call does call the controller method but it does not send the object from that I’m trying to send.I tried multiple solutions from Stackoverflow without success including using Json.stringify() method and using the [HttpPost] attribute in controller method.I also have the name of the object from View the same as the name of the controller method parameter.This is the script where I make the Ajax call:

    <script>

        $(document).ready(function () {

            
              $('.send-all').on('click', function() {
                    var data = $('#verticalScroll tr').map(function () {

                          var $row = $(this);
                          return {
                            id: $row.find('.id').text().trim(),
                            companyName: $row.find('.companyname').text().trim(),
                            price: $row.find('.price').text().trim(),
                            quantity: $row.find('.quantity').text().trim(),
                          }

                    }).get();

                      var BID = [];
                      for (var i = 0; i < data.length; i++) {
                          if (data[i].id != null && data[i].id != "") {                       
                              BID.push(data[i]);
                          }
                      }

                        $.ajax(
                        {

                            type: "POST",
                            url: "/User/UpdateBID",
                            data: BID,
                            cache: false,
                            async: true,
                            dataType: "json",
                            success: function (data) {
                                alert(data);
                      
                            },

                            });

              });

  
        });

    </script>

and this is the method from the controller :

   public ActionResult UpdateBID(object BID)
    {
        string c = JsonConvert.SerializeObject(BID);
        //Context.UpdateBID(b);
        return RedirectToAction("SesionIndividual", TempData["LoginModel"]);
    }

The controller method is called,but the object is null.I also made sure the JavaScript object is not null.I also tried to send other objects just to test it,and I have the same result,the parameter in the controller method is null.

3

Answers


  1. Chosen as BEST ANSWER

    For anyone interested I realize what the problem was.I was trying to send an JavaScript array of objects to a method which theoretically accepted an array of those objects.Well,apparently this did not work.What I did was to create a new object in C# with a property which had a type of UpdateOrder[],something like that:

    public class UpdateOrder
    {
        public int id { get; set; }
        public string companyName { get; set; }
        public string price { get; set; }
        public int quantity { get; set; }
    }
    
    public class Term
    {
        public UpdateOrder[] Terminal { get; set; }
    }
    

    I created a similar Term object in Javascript and send it through AJAX in controller method and it worked.So,instead of sending directly an array,I created an object with a property which holds that array.


  2. MVC will try to bind from model properties so there should be a property called BID

    data: { BID: BID }
    
    Login or Signup to reply.
  3. I have the name of the object from View the same as the name of the controller method parameter.

    The name of the object is irrelevant, as it’s just a variable name. This gets converted to the name data anyway – ie data:BID = data=BID so the “variable name” passed via ajax is “data”. The properties in that variable need to match.

    The short answer is you your “data” variable needs a property that matches the action parameter name, ie:

    data: { BID: BID },
    

    The long(er) answer is that the MVC model binder will attempt to match property names with your parameter names. In this case you’ve made it difficult on yourself by using object BID instead of an actual model, so there are no properties to match so it can only match on the parameter itself.

    If you created a model that matched the data being passed:

    public class BIDModel {
        public string companyName { get;set; }
        public string price { get;set; }
        public string quantity { get;set; }
    }
    

    and used that in your action

    public ActionResult UpdateBID(BIDModel BID) 
    

    then passing data: BID would work as the properties of data would be matched with the properties of BIDModel – you could still use data: { BID: BID } and the MVC model binder would match the data.BID property to your parameter name directly (and the properties within each would then be mapped).


    To cover:

    [HttpPost] attribute in controller method.

    the [HttpPost] attribute does not make it a post method – instead of restricts the http verb to POST. You generally don’t need this. It’s useful where you have two methods with the same name but different overloads and one for the GET with an equivalent POST (where the GET parameter is just an id but the POST is the full model). It can also be used as additional security.

    In your case, you are getting inside the action (just with a null parameter) so that part is clearly working fine.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search