Can any body help me out.
I have this code
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function GOTO() {
var datastring = "id=2";
$.ajax({
type: "POST",
url: "/Home/Index",
dataType: "json",
data: datastring,
success: function (json) { Complete(json.result); },
error: function (request, status, error) {
//alert("an error occurred: " + error);
alert("Error saving data. Please contact support.");
}
});
}
function Complete(result) {
if (result == "success") {
alert("Success");
}
else {
alert("Failed");
}
}
</script>
<input type="button" value="submit" onclick="JavaScript:GOTO()" />
</asp:Content>
and My C开发者_C百科ontroller Code is this
[HttpPost]
public System.Web.Mvc.JsonResult Index(string datastring)
{
return Json(new { foo = "bar", baz = "Blech" });
}
But it never hits my controller at all, is that Something I am doing wrong in my View?
thanks
Try passing the data
like this:
$.ajax({
type: "POST",
url: "/Home/Index",
dataType: "json",
data: { datastring: 'foo bar' },
success: function (json) { Complete(json.result); },
error: function (request, status, error) {
alert("Error saving data. Please contact support.");
}
});
function Complete(result) {
if (result == "success") {
altert("Success");
// ^ beware!
You have a syntax error in your code.
Moreover, you don't need to specify the JavaScript:
protocol in the onclick
attribute, you're merely defining a label at that place. Even better, don't assign event listeners in HTML attributes at all, but use unobtrusive JavaScript, including a fallback for the rare case when JavaScript is unavailable.
Update: if you get the "$.ajax
is undefined" error, you probably didn't include jQuery in your page. Add
<script type="text/javascript" src="path/to/jquery-X.X.X.js"></script>
To your page above the script
element that uses $.ajax
(or any other jQuery function).
it could be down to what data you are passing in. Your method expects a parameter called datastring but you are passing in 'id=2'.
精彩评论