0

I just started using .net and I'm trying to send data from a .html file to controller using AJAX. My ajax call:

var dataValue = {
            ID: 10,
            Name: 'Test'
        };
        $.ajax(
        {
            url: "/waitingList/apply",
            type: "POST",
            dataType: 'json',
            data: dataValue,
            success: function (result) {
                console.debug(result);
                alert(result);
            },
            error: function (xhr, status, p3, p4) {
                console.debug(xhr);
                var err = "Error " + " " + status + " " + p3;
                if (xhr.responseText && xhr.responseText[0] == "{")
                    err = JSON.parse(xhr.responseText).message;
                alert(err);
            }
        });

My controller:

[Route("waitingList/apply")]
public class WaitingListController : Controller
{
    [HttpPost]
    public string Post(WaitingList wList)
    {

        return string.Format("Test"); 
    }
}

When I run it, my AJAX return an error: "Not Found". I don't know why. My index.html is in the root and the controller in the controller folder of my MVC project. Does anyone know what I'm doing wrong?

3
  • 2
    Move your [Route("waitingList/apply")] to the method (not on the controller) Commented Jan 24, 2018 at 3:11
  • Thanks, but still the same problem Commented Jan 24, 2018 at 3:23
  • Have you enabled attribute routing? Just try by commenting it out and using url: "/waitingList/post",. And if that is still giving you a 404, post the full details of the error message Commented Jan 24, 2018 at 3:25

1 Answer 1

1

Change your controller like this.

public class WaitingListController : Controller
{
    [HttpPost]
    [Route("waitingList/apply")]
    public string Apply(WaitingList wList)
    {
        return string.Format("Test"); 
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks... Why do I need to change the name of the method to Apply? Sorry i am new
You do not need to change the method name to Apply. If that is what made it work, then clearly you did not set up attribute routing correctly.
Yes, it should also work without changing the name of the method if Attribute routing is enabled in MVC project. Add routes.MapMvcAttributeRoutes(); in your RouteConfig class and try.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.