简体   繁体   中英

asp.net MVC responding to jQuery AJAX request

I have the following code in a razor .cshtml file. Clicking a button should fire an ajax GET request which should pop up an alert with whatever data the server returned. (the JS below is within document.ready)

    $("#ajax-form").click(function () {

        alert("event fired");

        $.ajax({
            url: '/apartments/getData',
            type: 'GET',
            dataType: "text",
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                alert("Error");
            }
        });
    });

And the view code:

<div class="row">
    <form id="ajax-form">
        <input type="submit"/>
    </form>
</div>

Here is the controller code:

    [HttpGet]
    public string getData()
    {
        return "Some dummy data here";
    }

The event is definitely firing but the request fails (the error function fires). I could not get this to work with $.post or $.get either. Also typing localhost:54637/apartments/getData opens a page with "Some dummy data here".

Any ideas? Is there some particular way an asp.net MVC route must be settup to respond to an AJAX request?

you can use form submit event, when form is submitted ajax request will be sent:

$(document).ready(function(){  

$("#ajax-form").submit(function () {

        alert("event fired");

        $.ajax({
            url: '@Url.Action("getData","apartments")',
            type: 'GET',
            dataType: "html",
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                alert("Error");
            }
        });
    });
});

or you can use submit button click event like this:

$(document).ready(function(){  

$('#ajax-form input[type="submit"]').click(function () {

        alert("event fired");

        $.ajax({
            url: '@Url.Action("getData","apartments")',
            type: 'GET',
            dataType: "html",
            success: function (data) {
                alert(data);
            },
            error: function (data) {
                alert("Error");
            }
        });
    });
});

Update:

you can post form via ajax this way:

$(document).ready(function(){  

    $("#ajax-form").submit(function (e) {
     var form = $(this);
            alert("event fired");

            $.ajax( {
      type: "POST",
      url: form .attr('action'),
      data: form.serialize(),
      success: function( response ) {
        console.log( response );
      }
    } );

       e.preventDefault(); //STOP default action
       e.unbind(); //unbind. to stop multiple form submit.
        });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM