Reputation: 9377
I'm trying to use Ajax.BeginForm() to POST A Json result from my controller (I'm using MVC3). When the Json result is called it should be sent to a javascript function and extract the object using
var myObject = content.get_response().get_object();
However it just throws a "Microsoft JScript runtime error: Object doesn't support this property or method" when trying to invoke the Ajax POST.
My code:
Controller:
[HttpPost]
public ActionResult Index(string message)
{
return Json(new { Success = true, Message = message });
}
View:
<!DOCTYPE html>
<html>
<head>
<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
<script type="text/javascript">
function JsonAdd_OnComplete(mycontext) {
var myObject = mycontext.get_response().get_object();
alert(mycontext.Message);
}
</script>
</head>
<body>
<div>
@using(Ajax.BeginForm("Index", "Home", new AjaxOptions() { HttpMethod = "POST", OnComplete = "JsonAdd_OnComplete" }))
{
@Html.TextBox("message")
<input type="submit" value="SUBMIT" />
}
</div>
</body>
</html>
The strange thing is that the exactly same code works in MVC2 - Is this a bug, or have I forgot something?
Thanks in advance.
Upvotes: 3
Views: 2443
Reputation: 30208
if you are using the method provided by BuildStarted, here's how to structure the eval:
var json = eval("(" + context.responseText + ")");
Upvotes: 0
Reputation: 1038730
AFAIK in ASP.NET MVC 3 RC MS AJAX has been deprecated in favor of jQuery which is used by all Ajax.*
helper methods. Javascript has become unobtrusive as well. This means that you no longer have to call .get_response().get_object()
but simply:
function JsonAdd_OnComplete(myObject) {
// here myObject is already the JSON object
// as returned by the controller action
alert(myObject.Message);
}
Upvotes: 3
Reputation: 26689
Have you looked at the OnSuccess
method? When that method is called the object passed to it is a JSON object based on a JSONResult so you could do this...
<script type="text/javascript">
function JsonAdd_OnSuccess(mycontext) {
alert(mycontext.Message);
}
</script>
@using(Ajax.BeginForm("Index", "Home",
new AjaxOptions() {
HttpMethod = "POST",
OnSuccess = "JsonAdd_OnSuccess" })) {
@Html.TextBox("message")
<input type="submit" value="SUBMIT" />
}
In addition the OnComplete method returns an object that contains the following properties
context.responseText
context.responseBody
context.responseXml
You'll have to eval()
the responseText to convert the text to JSON though.
Upvotes: 1