I want to call a server side method using Jquery getJSON with .NET 3.5, MVC2 and JQuery1.4.1.
I've followed some online tutorials, but cannot get the serverside method to return anything other than null. All 3 alerts are fired in the JS below, and I can hit a break point on my server side method (also below). As I'm starting out, I've included all the client side code just in case I have done something stupid. Any idea what I am doing wrong - I've spent ages trying to get a value back from the server. Many thanks.
My client code is: (Each line is missing the beginning <)
<@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.M开发者_StackOverflow中文版vc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script>
function test()
{
alert("Here");
$.getJSON(
"/Home/Test", null, function(data, status) { alert("Success!"); alert(data); });
};
</script>
<asp:Button ID="Button1" runat="server" Text="Call Page Methods" OnClientClick="return test()"/>
</form>
</asp:Content>
And my server side code is:
public JsonResult Test()
{
string fooString = "test";
return Json(fooString, JsonRequestBehavior.AllowGet);
}
I think you are mixing some notions here. ASP.NET and ASP.NET MVC is not the same thing. From your code snippet I assume this is an ASP.NET MVC application (your view inherits from System.Web.Mvc.ViewPage
). In ASP.NET MVC application <asp:Button runat="server"
and <form runat="server">
and <asp:ScriptManager
are no longer used, you can forget about those and there are no page methods, there are controllers and actions.
So you could do the following in your view:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$('#btnTest').click(function() {
$.getJSON('/Home/Test', null, function(data) {
alert("Success!");
});
return false;
});
</script>
<input type="button" id="btnTest" name="test" />
</asp:Content>
精彩评论