Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC post with data and return json data

I have a controle like this

public JsonResult GetSizes(long Id)
    {
        try
        {
            //get some data and filter y Id

        }
        catch (Exception ex) {  }
        return Json(//data);
    }

I need to get that by following json by ajax request

var sizes = [];
$.ajax({
    type: 'POST',
    async: false,
    data: { 'Id': selectedId },
    url: "/<Controler name>/GetSizes",
    dataType: 'json',
    contentType: 'application/json; charset=utf-8',
    error: function (xhr) {
        alert('Error: ' + xhr.statusText);
        return false;
    },
    success: function (result) {
        if (result.Result != null) {
            if (result.Result.length > 0) {
                sizes = result;
            }
        }
    }
});

But this give me an Server error. How can i fix this.

like image 786
Tharindu Ranasingha Avatar asked Aug 05 '26 05:08

Tharindu Ranasingha


1 Answers

replace your

url: "/<Controler name>/GetSizes",

by

url: "@Url.Action("GetSizes", "Controller_Name"),

and is you Ajax will have to be

async: false?


then try to use this as your Action

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult GetSizes(long Id)
{
    try
    {
        //get some data and filter y Id

    }
    catch (Exception ex) {  }
    return Json(//data);
}

Also, try to put a break point on your action and see in debug mode if your Ajax reaches your Action.

like image 112
evilom Avatar answered Aug 06 '26 18:08

evilom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!