aBlaze
aBlaze

Reputation: 2716

AJAX call in ASP.NET MVC application not calling Action method

I have the following ASP.NET MVC .cshtml file in which I do the following: Grab the Name & Id values from MyObject and create a DropDownList out of them, when the user selects an item in the Drop Down box I attempt to use AJAX to call TheMethodToCall which is a method in TheController, and attempt to display the text result returned by TheMethodTocall.

@model List<MyWebApp.Models.MyObject>

@if (Model.Count > 0)
{
    using (Html.BeginForm())
    {
        <div class="input-group mb-3">
            @Html.DropDownList("SelectFromDropdownList", Model.Select(i => new SelectListItem()
                {
                    Text = i.Name,
                    Value = i.Id
                }), "This is the default DropDownList option", new { @class="custom-select", @id="mydropdownid"})
            <script>
                $(function(){
                    $('#SelectFromDropdownList').change(function () {
                        var typeFeed = $(this).val();
                        // Perform AJAX call
                        $.get("@Url.Action("TheMethodToCall", "TheController")", { TypeFeed: typeFeed }, function (result){
                            @Html.DisplayText(result);
                            });
                        });
                    });
            </script>
        </div>
    }
}

I'm having a couple of issues, please help! Here they are:

  1. I have put my Visual Studio debugger breakpoint in the TheMethodToCall method, but it does not get hit when the user selects an item from the DropDownList.
  2. Is this the correct way of displaying the result text which is returned form TheMethodToCall?

Update

I appreciate the answers so far, but I'm setting a breakpoint in this method, but it is still not being called. I did change $('#SelectFromDropdownList').change(function () to $('#mydropdownid').change(function (). Is there anything else to do?

    [WebMethod()]
    public static string TheMethodToCall()
    {
        return "This is a test";
    }

Upvotes: 0

Views: 429

Answers (1)

ash
ash

Reputation: 532

  1. Your .change listener is using the wrong ID. The dropdown list has ID of mydropdownid but in your jQuery you have $('#SelectFromDropdownList').change. Change it to $('#mydropdownid').change

  2. The way you're using the result in the AJAX response isn't correct. You're trying to use server-side Razor/C# (which executes when the page initially loads) to handle a response that occurs long after the page has loaded. You need to use JavaScript only in the response function.

Upvotes: 1

Related Questions