aruni
aruni

Reputation: 2752

The resource cannot be found in Ajax function

I'm using C# asp.net mvc. I wrote a Ajax function in my Home controller - > index.cshtml.

<script type="text/javascript">

    $(document).ready(function () {       

        $.ajax({
            type: 'POST',
            dataType: 'html',
            url: '@Url.Action("getAlerts","Home")',
            data: ({}),
            success: function (data) {
                $('#alertList').html(data);


            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });

    }); 


  </script>

this is my function in Home controller

public IList<tblInsurance> getAlertsIns()
        {
            var query = (from i in db.tblInsurances
                        where i.status == true && i.EndDate <= DateTime.Today.AddDays(7)
                         select i).ToList(); ;


            return query;
        }

        public string getAlerts()
        {
            string htmlval = "";


            var InsExpirList = getAlertsIns();


            if (InsExpirList != null)
            {
                foreach (var item in InsExpirList)
                {
                    htmlval += item.tblContractor.Fname + " " + item.EndDate + "<br />";
                }
            }

            return htmlval;
        }

But ther is error and it says " The resource cannot be found."

POST http://localhost:49368/Home/getAlerts  404 Not Found 

what is wrong with my code?

Upvotes: 1

Views: 6586

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

If you want your controller action to accept POSTs, you must decorate it with an attribute specifying that fact:

[HttpPost]
public string getAlerts()
{
    // ...
}

In this case, however, it seems like a GET request would be more appropriate (your action is called getAlerts after all). If that's the case you can omit the accepted verb, or use [HttpGet] instead. You would also have to change your AJAX request:

$.ajax({
    type: 'GET',
    dataType: 'html',
    url: '@Url.Action("getAlerts","Home")',
    /* ... */
});

Upvotes: 4

Related Questions