Mickey Perlstein
Mickey Perlstein

Reputation: 4024

MVC 5 JsonResult returns html?

I have been following this tutorial https://www.youtube.com/watch?v=c_MELPfxJug regarding ajax and JsonResult in HomeController

I did the tutorial, however for some reason the controller is returning Html and not json

I did not change one line of code, but it's failing with parseError on the javascript side.

when i look at the response i see an html page, not a json object.

Controller code:

    public JsonResult DoubleValue(int? Value)
    {
        if (!Request.IsAjaxRequest() || !Value.HasValue)
        { return null; }
        else
        {
            int DoubleValue = Value.Value * 2;
            var ret =  new JsonResult
            {
                Data =
                    new { DoubleValue = DoubleValue }
            };
            return ret;
        }
    }

cshtml:

@using (Html.BeginForm())
{

    @Html.TextBox("txtAmount",0)
     <button id="btnDoubleValue">DoubleIT</button>
    <div id="lblMessage"></div>

}

@section Scripts{
<script type="text/javascript">
    $(function () {
        $('#btnDoubleValue').on('click', function() {

             $.ajax({
                 type: 'POST',
                 url: '@Html.Action("DoubleValue")',
                 data: { 'Value': $('#txtAmount').val() },
                 datatype: 'json',
                 cache: 'false'
             }).success(function (data) {

                 var t = data;

                 $('#txtAmount').val(data.DoubleValue);
             }).error(function (x, o, e) {
                 $('#lblMessage').html('error was found: ' );
             });

            return false;
        })
    });

    </script>
   }

Upvotes: 1

Views: 3704

Answers (2)

Mickey Perlstein
Mickey Perlstein

Reputation: 4024

found the error I was using Html.Action and not Url.Action -> just human error I suppose

from the reference:

   Html.Action - returns the result as an HTML string.

It works now

        $.ajax({
             type: 'POST',
             url: '@Url.Action("DoubleValue")', //<--- Url.Action
             data: { 'Value': $('#txtAmount').val() },
             datatype: 'json',
             cache: 'false'

Upvotes: 2

Menelaos Vergis
Menelaos Vergis

Reputation: 3935

I guess this must be the default error page, you are probably getting a 500 response and you must use the Network tab of your browser to see the real problem.

  • In your browser open developer tools using F12 key and navigate to Network tab.
  • Make the appropriate actions to do the ajax request (click on that button)
  • Click on the request row
  • Navigate to Response tab.

From there you can watch the real request your ajax does and the response from the server.

Upvotes: 1

Related Questions