Mehdi
Mehdi

Reputation: 598

Posted model to controller via ajax is null

I'm trying to send just 2 ID's to the controller by Ajax as below, but the model is null at all.

My view model is so simple as below:

public class CityAreaBindingModel
{
    public int CityID { get; set; }
    public int AreaID { get; set; }
}

View: two dropdown list which helps to select City and Area

        <select class="form-control" id="CityID" name="CityID">
            @{
                foreach (var city in ViewData["Cities"] as List<SamsungTools.Models.City>)
                {
                    <option value="@city.ID" @(city.ID == 1 ? "selected" : "")>@city.Title</option>
                }
            }
        </select>
        <select class="form-control" id="AreaID" name="AreaID">
            @{
                foreach (var area in ViewData["Areas"] as List<SamsungTools.Models.Area>)
                {
                    <option value="@area.ID" @(area.ID == 1 ? "selected" : "")>@area.Title</option>
                }
            }
        </select>

Ajax: using formData with two selected id from view

var cId = $('#CityID').val();
var aId = $('#AreaID').val();
var data = new FormData();
data.append("CityID", cId);
data.append("AreaID", aId);

$.ajax({
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    type: 'POST',
    url: '/api/GetData/GetSaleCentersByLocation',
    data: data,
    processData: false,

And in controller just getting view model passed from ajax:

[HttpPost]
public JsonResult GetSaleCentersByLocation(CityAreaBindingModel model)
{
    GeneralStore gs = new GeneralStore();
    var saleCentersByCity = gs.GetSaleCentersByCity(model.CityID);
    var result = new JsonResult();
    result.Data = saleCentersByCity;
    result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

    return result;
}

The problem is that the model is null in the controller at all. I changed header's fields in Ajax but in any other way I will get error 415, Illegal Invoke, server error 500, ... With the above Ajax options, data will send to controller but model is null.

Any solution?

Upvotes: 2

Views: 131

Answers (2)

Hamed Moghadasi
Hamed Moghadasi

Reputation: 1673

I think the problem is from your data structure in js code, try below code:

var cId = $('#CityID').val();
var aId = $('#AreaID').val();

var jsonObject = {"CityID": cId , "AreaID": aId };
var data = JSON.stringify(jsonObject);

$.ajax({
    'Content-Type': 'application/json'
    type: 'POST',
    url: '/api/GetData/GetSaleCentersByLocation',
    contentType: "application/json",
    data: data
    success: function (result) {
     console.log(result);
    }
});

Upvotes: 3

Hien Nguyen
Hien Nguyen

Reputation: 18975

Your code has some problem: incorrect ajax call format, did not stringify data and may be your url routing incorrect. Here are code for your requirement. I mocked up some functions

 public class CityAreaBindingModel
    {
        public int CityID { get; set; }
        public int AreaID { get; set; }
    }

    public class City
    {
        public int ID { get; set; }
        public string Title { get; set; }
    }

    public class Area
    {
        public int ID { get; set; }
        public string Title { get; set; }
    }

    public class SaleController : Controller
    {
        public ActionResult GetSaleCentersByLocation()
        {
            ViewData["Cities"] = new List<City>
            {
                new City {ID = 1, Title = "Hanoi"},
                new City {ID = 2, Title = "SaiGon"}
            };

            ViewData["Areas"] = new List<Area>
            {
                new Area {ID = 1, Title = "Area1"},
                new Area {ID = 2, Title = "Area2"}
            };
            return View();
        }


        [HttpPost]
        public JsonResult GetSaleCentersByLocation(CityAreaBindingModel model)
        {
            GeneralStore gs = new GeneralStore();
            var saleCentersByCity = gs.GetSaleCentersByCity(model.CityID);
            var result = new JsonResult();
            result.Data = saleCentersByCity;
            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            return result;
        }
    }

    public class GeneralStore
    {
        public object GetSaleCentersByCity(int modelCityId)
        {
            return new { Id = 1, Name = "Test"};
        }
    }

View for controller GetSaleCentersByLocation.cshtml

@using WebApplication1.Controllers

<select class="form-control" id="CityID" name="CityID">
    @{
        foreach (var city in ViewData["Cities"] as List<City>)
        {
            <option value="@city.ID" @(city.ID == 1 ? "selected" : "")>@city.Title</option>
        }
    }
</select>
<select class="form-control" id="AreaID" name="AreaID">
    @{
        foreach (var area in ViewData["Areas"] as List<Area>)
        {
            <option value="@area.ID" @(area.ID == 1 ? "selected" : "")>@area.Title</option>
        }
    }


</select>

<button onclick="test();">Post data</button>
<script>
    function  test() {
        var cId = $('#CityID').val();
        var aId = $('#AreaID').val();
        var data = {
            CityID: cId,
            AreaID : aId
        };


        $.ajax({
            type: 'POST',
            contentType: "application/json",
            dataType: 'JSON',
            url: 'GetSaleCentersByLocation',
            data: JSON.stringify(data),
            processData: false,
            success: function (result) {
                alert(data);
            }
        });

    }

</script>

Upvotes: 0

Related Questions