behzad razzaqi behzad razzaqi - 3 months ago 11
Ajax Question

Why i can not call the controller from ajax in asp.net mvc?

I'm beginner in

asp.net mvc
,i want to call the controller action from Ajax code ,for that purpose read this tutorial:

CALL CONTROLLER WITH AJAX


write this action method in my controller:


[HttpPost]
public void Test01()
{
string behzad = "BEHZAD RAZZAQI";

}




and in view page write this html code:


<button type="button" id="btn1" class="btn btn-success">ثبـت نـام</button>




in on that view page write this
jquery
code:


<script>
$("#btn1").click(function () {
$.ajax({
url: "/MainPage/Test01",
datatype: "text",
type: "POST",
success: function (data) {
alert('ok');//$('#testarea').html("All OK");
},
error: function () {
$("#testarea").html("ERROR");
}
});
});
</script>




but when i fire the button i can not see any alert,what happen?how can i solve that problem?

Answer

Try this instead:

 $(document).ready(function() {

    $("#btn1").click(function () {
        $.ajax({
            url:'<%= Url.Action("Test01", "MainPage") %>',
            success: function(data) {
                 alert("ok");
            }
        });
    });

 });

Make sure that MainPage is the name of your controller and that you included your jquery library, just like @bhupesh stated:

<script src="~/scripts/jquery-*.*.*.min.js"></script>

Further information can be found Here

Comments