ASPCoder1450
ASPCoder1450

Reputation: 1651

JSON Undefined Error in ASP.NET MVC

I have this JS function:

    <script type="text/javascript">
    $(function ShowBMI() {
        $.getJSON('/BMICalculations/ShowBMI', function (data) {
            alert(data.CalculatedBMIResult);
        });
    });

And in my BMICalculations controller I have this method:

 public JsonResult ShowBMI(){
        BMICalculation BMI = new BMICalculation();
        var data = Json(new
        {
            CalculatedBMIResult = 6
        });
        return Json(data, JsonRequestBehavior.AllowGet);
    }

I call the JS function using the Onclick event of my submit button. The JS alert says 'undefined'. My Chrome console says that ShowBMI() is undefined but how could this be? Since its defined properly in my controller?

Upvotes: 0

Views: 1379

Answers (1)

nemesv
nemesv

Reputation: 139758

The Json method returns a JsonResult object and not the converted JSON.

So you will end up wrapping your data to a JsonResult and sending the wrapper object to your client instead of your original data.

To fix this you just need to remove your first Json call when creating the data:

public JsonResult ShowBMI()
{
    BMICalculation BMI = new BMICalculation();
    var data = new
    {
        CalculatedBMIResult = 6
    };
    return Json(data, JsonRequestBehavior.AllowGet);
}

Upvotes: 2

Related Questions