Home > database >  ASP.NET MVC JSON get value with two Parameters
ASP.NET MVC JSON get value with two Parameters

Time:10-27

I am trying to get value based on 2 parameters, below is my function where I added my 2 parameters in JSON stringify :

function GetItemLocationOnHand(itemId, locationId) {
    var data = JSON.stringify({
        itemId: itemId,
        locationId: locationId
    });
    $.ajax({
        async: true,
        type: 'GET',
        dataType: 'JSON',
        contentType: 'application/json; charset=utf-8',
        data: data,
        url: 'getItemInventory3',
        success: function (data) {
            $("#txtInventory3").val(parseFloat(data).toFixed(2));
    
        },
        error: function () {
            alert("Error")
    
        }
    });
}

Below is my code in my controller to retrieve the data I want based on these two parameters :

[HttpGet]
public JsonResult GetItemLocationOnHand(int itemId, int locationId)
{
    var itemLocQuantity = objDB.ItemLocationDatas.Single(items => items.ItemId == itemId && items.LocationId == locationId).Quantity;
    return Json(itemLocQuantity, JsonRequestBehavior.AllowGet);
}   

Upon calling this function via below on change code, I can't seem to get my data and is always returning the error.. If I only have 1 parameter, then no error encountered.

Please advise what went wrong when trying to pass 2 parameters.

$("#LocationId").change(function () {
    var itemId = $("#ItemId").val();
    var locationId = $("#LocationId").val();

    GetItemLocationOnHand(itemId, locationId)
});

CodePudding user response:

Issue solved by doing the following :

  • added correct URL which is GetItemLocationOnHand

  • removed Stringify and used var data = ({ itemId: itemId, locationId: locationId });

thanks a lot to Freedom and Reflective and others for your comments!

 function GetItemLocationOnHand(itemId, locationId) {
        var data = ({ itemId: itemId, locationId: locationId });


        $.ajax({
            async: true,
            type: 'GET',
            dataType: 'JSON',
            contentType: 'application/json; charset=utf-8',
            data: data,
            url: 'getItemLocationOnHand',
            success: function (data) {
                $("#txtInventory3").val(parseFloat(data).toFixed(2));

            },
            error: function () {
                alert("Error")

            }
        });

    }

CodePudding user response:

Just to avoid some misunderstanding how AJAX GET works and setting some parameters which you don't have to set (i.e. you are still not so deep into jQuery AJAX) you may use the shortcut they also implemented i.e. $.get so your request will look as simple as that and you can't get wrong as it will use the proper defaults for GET. If you want the response to be treated as JSON, just set Content-type of your response headers (from backed) to application/json. This will be checked by jQuery AJAX response handler and it will parse the incoming data as JSON.

    var data = {itemId: 1, locationId: 2 };
    $.get('GetItemLocationOnHand', data, function (data) {
      $("#txtInventory3").val(parseFloat(data).toFixed(2));    
    }).fail(function (jqXHR, textStatus ) {
      alert(`Error = ${jqXHR.status} ${textStatus}`);
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

welcome to Stackoverflow.com. :)

See my example below. This works for me when doing ajax requests to a MVC controller with multiple params.

  1. Below is my MVC controller action with multiple params.

     // GET
     [HttpGet]
     public ActionResult Index(string referenceID, int typeID, int supplierID, bool isArchived)
     {
         // Do CODE here
     }
    
  2. Below is my Ajax request that I use to get or post. Depending on your needs. I use data type 'JSON' and format my data as a JSON object.

           var formData = {referenceID: 'Test', typeID: 3, supplierID: 2, isArchived: false};
           $.ajax({
             type: 'GET',
             cache: false,
             url: getActionUrl, // url: domain/controller/action |or| domain/area/controller/action
             dataType: 'json',
             contentType: 'application/json; charset=utf-8',
             headers: headers, // ignore if not needed. I use it for __RequestVerificationToken
             data: formData,
             success: function (data, status, xml) {
                 // do something with the data
             },
             error: function (xml, status, error) {
                 console.log(xml)
                 // do something if there was an error
             },
             complete: function (xml, status) {
             }
         });
    

I think your issue might be that you are using 'JSON.stringify'. It could be interpreting your JSON string as a single parameter input and not two separate parameters.

Please see below snippets from documentation. https://api.jquery.com/jquery.ajax/

  • If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.
  • The data option can contain either a query string of the form key1=value1&key2=value2, or an object of the form {key1: 'value1', key2: 'value2'}. If the latter form is used, the data is converted into a query string using jQuery.param() before it is sent. This processing can be circumvented by setting processData to false. The processing might be undesirable if you wish to send an XML object to the server; in this case, change the contentType option from application/x-www-form-urlencoded to a more appropriate MIME type.
  • Related