0

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?

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.