Home > Web Front-end > JS Tutorial > body text

How to Resolve JavaScript Alert Not Firing in AJAX Call to ASP.NET MVC Controller?

Mary-Kate Olsen
Release: 2024-10-18 22:18:30
Original
660 people have browsed it

How to Resolve JavaScript Alert Not Firing in AJAX Call to ASP.NET MVC Controller?

Making an Ajax Call to a Controller in ASP.NET MVC

Problem:

When attempting to retrieve data from a controller via Ajax, a JavaScript alert is not firing, despite the controller method returning the expected result.

Solution:

  1. Remove the data attribute: Since the controller method does not expect any parameters, the data attribute should be removed from the Ajax request.
  2. Use Razor and @Url.Action: Dynamically generate the URL for the Ajax request using Razor syntax and the @Url.Action helper method:
<code class="javascript">$.ajax({
    url: '@Url.Action("FirstAjax", "AjaxTest")',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: successFunc,
    error: errorFunc
});</code>
Copy after login

Updated Code with POST Data (Optional):

If the controller method requires POST data, it can be passed through the data attribute:

<code class="javascript">$.ajax({
    type: "POST",
    url: '@Url.Action("FirstAjax", "AjaxTest")',
    contentType: "application/json; charset=utf-8",
    data: { a: "testing" },
    dataType: "json",
    success: function() { alert('Success'); },
    error: errorFunc
});</code>
Copy after login

The above is the detailed content of How to Resolve JavaScript Alert Not Firing in AJAX Call to ASP.NET MVC Controller?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!