ASP.NET execute method through AJAX

1

Hi, I'm learning to use AJAX in ASP NET, I want to run a method through js, but I'm not sure how to reference it, the method I want is in my controller but when I give it the route it does not tell me it does not find anything .

@model PCotiza_compras.Models.Departments
@{
    ViewBag.Title = "Kyo_2";

}
<script src="~/Scripts/jquery-1.10.2.js"></script>
<div id="Content"></div>
<input type="button" name="name" value="try" onclick="DepListQuery()" />

<script>

    function DepListQuery() {

        $.ajax({
            type: 'POST',
            url: '../../Controllers/HomeController/.GetData()', //aquí no sé si estoy bien D:
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                    
                $("#Content").text(response.d);
            },
            failure: function (response) {
                alert(response.d);
            }
        });
    }

</script>

And this is the method in my controller

 [Authorize]
        public ActionResult Kyo2()
        {
          

                return View();


        }// End Get/kyo 2

        [WebMethod]
        public static string GetData()
        {
            return "This string is from Code behind";
        }
Thank you all so much for your help :)     
asked by E.Rawrdríguez.Ophanim 29.09.2017 в 21:41
source

2 answers

1

First, on your backend:

[WebMethod]
public static string GetData()
{
    return "This string is from Code behind";
}

By:

[HttpGet]
public ActionResult GetData()
{
    return Content("This string is from Code behind");
}

Now, in the frontend, in your JavaScript, replace:

url: '../../Controllers/HomeController/.GetData()'

By:

url: '@Url.Action("GetData","Home")'

Keep in mind that using an AJAX type: 'POST' goes with an [HttpPost] in the controller.

By using an action with the [HttpGet] attribute on the controller, it makes an AJAX type: 'GET'

Edit

Replaces:

$("#Content").text(response.d);

By:

$("#Content").text(response);

Reason:

You are getting a direct string so the "d" property is without definition.

Finally, I suggest you take some classes in link about ASP.net MVC, in the same way, here I leave you a workshop that we made with the brotherhood of StackOverflow in Spanish: link the code of that project is on GitHub in the description of the video .

    
answered by 30.09.2017 / 00:47
source
1

Only the name of the controller WITHOUT the word controller is placed in the url. You also remove the "." and the "()" as seen below:

url: '../../Controllers/Home/GetData'
    
answered by 29.09.2017 в 21:58