0

I'm trying to POST an int with Ajax to my controller

Js

<script>
    function FillCity() {
        var provinceId = $(provinces).val();
        $.ajax({
            url: "FillCity",
            type: "POST",
            data: { id: provinceId },
            dataType: "json",
            traditional: true,
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $("#cities").html(""); // clear before appending new list
                $.each(data, function (i, city) {
                    $("#cities").append(
                        $('<option></option>').val(city.Id).html(city.Name));
                });
            }
        });
    }
</script>

code in my controller :

[HttpPost]
public ActionResult FillCity(int id)
{
    var cities = _context.City.Where(c => c.ProvinceId == 5);
    return Json(cities);
}

but it always post 0 as id, I tried digits instead of provinceId, but it rtills send 0

Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41
Maryam
  • 47
  • 2
  • 10

3 Answers3

1

You should create an class that have a Id Property.

public class ProvinceIdDto 
{
    public int Id { get; set; }
}

replace int id with ProvinceIdDto model in action

[HttpPost]
public ActionResult FillCity(ProvinceIdDto model)
{
    var cities = _context.City.Where(c => c.ProvinceId == model.Id);
    return Json(cities);
}

replace { id: provinceId } with JSON.stringify({ Id: provinceId }),

<script>
    function FillCity() {
        var provinceId = $(provinces).val();
        $.ajax({
            url: "FillCity",
            type: "POST",
            data: JSON.stringify({ Id: provinceId }),
            dataType: "json",
            traditional: true,
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $("#cities").html(""); // clear before appending new list
                $.each(data, function (i, city) {
                    $("#cities").append(
                        $('<option></option>').val(city.Id).html(city.Name));
                });
            }
        });
    }
</script>

Another options is you can replace HttpPost method with HttpGet and pass id to action like this.

Change type: "POST", to type: "GET",

<script>
    function FillCity() {
        var provinceId = $(provinces).val();
        $.ajax({
            url: "FillCity?id="+provinceId,//<-- NOTE THIS
            type: "GET",//<-- NOTE THIS
            dataType: "json",
            traditional: true,
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                $("#cities").html(""); // clear before appending new list
                $.each(data, function (i, city) {
                    $("#cities").append(
                        $('<option></option>').val(city.Id).html(city.Name));
                });
            }
        });
    }
</script>

C#

[HttpGet]
public ActionResult FillCity(int id)
{
    var cities = _context.City.Where(c => c.ProvinceId == id);
    return Json(cities);
}
Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41
0

when you do { id: provinceId } you are creating an object with property id

in your controller you are just expecting an id. You will need to ether:

A pass it as a query parameter url: "FillCity?id=" + provinceId

B create an object to be parsed from the request body.

public class Payload {
   public int Id {get;set;}
}

and use it like this public ActionResult FillCity([FromBody] Payload payload)

Anton Toshik
  • 2,621
  • 2
  • 19
  • 42
0

Can you verify this statement has a value:

var provinceId = $(provinces).val();

It's possible that isn't finding what you are looking for, and because you have the type int as a parameter, it defaults it to "0".

You shouldn't need to change it to a GET and your MVC method is fine as is. You can see from JQuery's own sample it should work:

$.ajax({
  method: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });

I think it might not be finding the input field successfully.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
  • I said that I tested with digit like 5 and still doesnt work – Maryam Jul 24 '20 at 12:36
  • 1
    Try removing traditional: true because I do something similar to what you have but don't have that. Also per the attached link, you may want to use dataType, not contentType, since you are returning JSON: https://stackoverflow.com/questions/18701282/what-is-content-type-and-datatype-in-an-ajax-request/18701357#:~:text=3%20Answers&text=contentType%20is%20the%20type%20of,%2C%20html%20%2C%20text%20%2C%20etc. – Brian Mains Jul 24 '20 at 14:25