Search code examples
ajaxasp.net-corerazor-pages.net-7.0asp.net-core-tag-helpers

AJAX Calls in Tag Helpers Not Reaching in referenced project Controllers in .net 7


`I'm working on an ASP.NET Core razor page application where I use custom tag helpers from a separate project. These tag helpers make AJAX calls to various controllers in my main project. However, none of these AJAX calls seem to reach the intended controllers which is in a seperate project referenced in the main project, resulting in a 400 (Bad Request) error.

Here's an example AJAX call:

$.ajax({
    url: '/Intern/pages/edit?action=Put&controller=File', // This is the format I am using
    type: 'PUT', // or POST/DELETE, etc., based on the requirement
    data: JSON.stringify(someData),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        // Handle success
    },
    error: function (error) {
        // Handle error
    }
});

This call should theoretically trigger an action in my FileController, but it doesn't. Here's what the FileController looks like:

[ApiController]
[Route("[controller]")]
public class FileController : ControllerBase
{
    [HttpPut]
    public IActionResult PutMethod(MyModel model)
    {
        // Action logic
    }
}

However, the controller never gets executed. I've checked the following:

The controller is public and correctly set up with routing attributes. The AJAX URL, method, and data formats are correctly matched with the controller. No CORS issues; both the tag helper project and main project are on the same origin. My ASP.NET Core application is updated to .NET 7, and the issue persisted even after ensuring compatibility with the new version. I've also tried simplifying the controller action to a basic method to test connectivity, without success.

What might be causing these AJAX calls to fail in reaching the controllers? Any insights or suggestions would be greatly appreciated.

Feel free to modify this draft to include any additional details that you think are relevant, such as specific configurations or code snippets. Remember, the more precise and detailed your question, the more likely you are to receive helpful responses.`


Solution

  • None of these AJAX calls seem to reach the intended controllers which is in a seperate project referenced in the main project, resulting in a 400 (Bad Request) error.

    At a first glimps it can be said that your request URL is incorrect. It should be followed by your application host and port along with your controller and action name. For instance: following API should have this http://localhost:5094/api/File/PutMethod while calling from your razor page:

    [Route("api/[controller]")]
    [ApiController]
    public class FileController : ControllerBase
    {
        [HttpPut("PutMethod")]
        public IActionResult PutMethod(MyModel model)
        {
            return Ok($"Response from API is {model.Email}");
        }
    }
    

    Note: Make sure about your controller type, I have used API controller. If you use API controller so, razor page reference /Intern/pages/edit? is not required, just put your API controller full URL.

    Another point is very crucial that is API action signature. You would certainly encounter 400 if it doesn't match the parameter correctly.

    Let's have a look in practice how should we call the API from razor page ajax request.

    Razor page:

    @section scripts {
        <script>
            function PostAjaxRequest() {
    
    
                var _apiurl = "http://localhost:5094/api/File/PutMethod";
                var reqeustModel = {
                    Email: "[email protected]"
                };
                console.log(JSON.stringify(reqeustModel));
                $.ajax({
                    type: 'PUT',
                    url: _apiurl,
                    data: JSON.stringify(reqeustModel),
                    contentType: 'application/json',
                    headers: {
                        RequestVerificationToken:
                            $('input:hidden[name="__RequestVerificationToken"]').val()
                    },
                    success: function (data) {
                        console.log(data);
                        alert('Data sent to backend!');
                    },
                    error: function (xhr, status, error) {
                        alert('Data was not sent to backend!');
                    }
                });
    
                
            }
        </script>
    }
    

    Note: I have slidely modified your code as I like to put api prefix in my API so that I can understand which one is API controller and which one are MVC controllers. In addition, I have used headers which is optional for API request but required for calling razor page endpoint.

    Demo Request Model:

    public class MyModel
     {
         public string? Email { get; set; }
     }
    

    Output:

    enter image description here

    enter image description here