ASP.NET MVC3 - error using Javascript

I am trying to use Ajax.BeginForm () for a POST A Json result from my controller (I am using MVC3). When the Json result is called, it should be sent to the javascript function and the object extracted using

var myObject = content.get_response().get_object();

However, it simply throws a "Microsoft JScript Runtime Error: Object does not support this property or method" when trying to call AJAX POST.

My code is:

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 exact same code works in MVC2 - is it a mistake, or am I forgetting something?

Thanks in advance.

+3
source share
3 answers

AFAIK ASP.NET MVC 3 RC MS AJAX jQuery, Ajax.*. Javascript unobtrusive. , .get_response().get_object(), :

function JsonAdd_OnComplete(myObject) {
    // here myObject is already the JSON object 
    // as returned by the controller action
    alert(myObject.Message);
}
+3

OnSuccess? , , , JSON JSONResult, ...

<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" />

}

, OnComplete ,

context.responseText
context.responseBody
context.responseXml

eval() responseText, JSON.

+1

, BuildStarted, , eval:

var json = eval("(" + context.responseText + ")");
0

Source: https://habr.com/ru/post/1782306/


All Articles