charitht99 perera
charitht99 perera

Reputation: 325

Data passing error from javascript to controller

I'm working on ASP.NET MVC project , I want to get location dropdown selected value and according to that i need to load values to City dropdown , i implemented following code and location dropdown onselect event call the javascript function and javascript function call the controller method but when executing controller method locationId is null ,and i debug javascript and locationID is there till the this line data: JSON.stringify({ locationId: +locationId }), after that javascript returns error.but controller method get hit but locationId null

code for dropddowns

  <div class="row">
    <div class="col-sm-4">
        @Localizer["Locations"]
        <select id="locationDropDown"  class="selectpicker form-control" asp-for="selectedLocation" onchange="getCityList()">
            <option value="0">&lt;None&gt;</option>
            @foreach (var item in Model.LocationList)
            {
                <option value="@item.Id">@item.Name</option>
            }
        </select>
    </div>
</div>
<div class="row">
    <div class="col-sm-4">
        @Localizer["KioskGroup"]
        <select id="cityDropDown" class="selectpicker form-control">
            <option>---Select City---</option>
        </select>
    </div>
</div>

Javascript code

function getCityList()
        {
        debugger;
            var locationId = $("#locationDropDown").val();
            console.log(locationId)
        $.ajax({
            url: '/Kiosk/GetZoneListBYlocationID',
            type: 'POST',
            datatype: 'application/json',
            contentType: 'application/json',
            data: JSON.stringify({ locationId: +locationId }),
            success: function (result) {
                $("#cityDropDown").html("");
                $("#cityDropDown").append
                ($('<option></option>').val(null).html("---Select City---"));
                $.each($.parseJSON(result), function (i, zone) 
                { $("#cityDropDown").append($('<option></option>').val(zone.Id).html(zone.Name)) })

            },
            error: function(){alert("Whooaaa! Something went wrong..")},
        });

controller method

  public ActionResult GetZoneListBYlocationID(string locationID)
        {
            List<Zone> lstZone = new List<Zone>();
            long locationId = long.Parse(locationID);

            var zones = _zoneRepository.GetZonesByLocationId(locationId);

            return Json(JsonConvert.SerializeObject(zones));
        }

Upvotes: 2

Views: 1323

Answers (3)

Shyju
Shyju

Reputation: 218812

Your current code is sending the json string {"locationId":101} in the request body because you specified the contentType as application/json. This is useful when you want to send an object with multiple properties and your action method parameter is a DTO/POCO class type. Model binder will be reading from the request body and map it to the parameter.

In your case, all you are sending is a single value. So do not send the JSON string. simply create a js object and use that as the data attribute value. Also remove the contentType: application/json as we are not sending a complex js object as json string.

Also application/json is not a valid option for the dataType property. You may use json. But jQuery is smart enough to guess the value needed here from the response headers coming back from server. So you may remove it.

function getCityList() {

    var locationId = $("#locationDropDown").val();
    $.ajax({
        url: '/Kiosk/GetZoneListBYlocationID',
        type: 'POST',
        data: { locationID: locationId },
        success: function (result) {
           console.log(result);
           // populate dropdown
        },
        error: function () { alert("Whooaaa! Something went wrong..") },
    });

}

Now this data will be send in Form Data as locationID=101 with Content-Type header value as application/x-www-form-urlencoded and will be properly mapped to your action method parameter.

You should use the correct types. In your action method, you are using string as your parameter and later trying to convert it to long. Why not use long as the parameter type ? Also if zones variable is a list of Zone object, you can pass that directly to the Json method. No need to create a string version in between.

 public ActionResult GetZoneListBYlocationID(long locationId)
 {
    var zones = _zoneRepository.GetZonesByLocationId(locationId);
    return Json(zones);
 }

Upvotes: 1

Dhrutika Rathod
Dhrutika Rathod

Reputation: 560

I was facing the same problem. and after that, I have tried below solution. Hope it will help you.

ajax call is as follows:

          $.ajax({
                type: 'POST',
                url: "/Account/GetCities",
                dataType: 'json',
                data: { id: $("#StateID").val() },
                success: function (states) {
                    $.each(states, function (i, state) {
                       $("#CityID").append('<option value="' + state.Value + '">' + state.Text + '</option>');
                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve cities.' + ex);
                }
            });

The controller code is as follows:

public List<CityModel> GetCities(int id)
{
        //your code
}

You can do in your application like this:

function getCityList()
        {

            var locationId = $("#locationDropDown").val();
            console.log(locationId)
        $.ajax({
            url: '/Kiosk/GetZoneListBYlocationID',
            type: 'POST',
            dataType: 'json',
            data: { locationId: locationId },
            success: function (result) {
                $("#cityDropDown").html("");
                $("#cityDropDown").append
                ($('<option></option>').val(null).html("---Select City---"));
                $.each($.parseJSON(result), function (i, zone) 
                { $("#cityDropDown").append($('<option></option>').val(zone.Id).html(zone.Name)) })

            },
            error: function(){alert("Whooaaa! Something went wrong..")},
        });
}

And your controller will be same as you have done.

Upvotes: 0

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

Why you are stringify the data.Below one should work without stringify

data: { locationId: +locationId },

Upvotes: 1

Related Questions