0

I am trying to do an ajax call from my view where I return a json object from my controller. However, when I try this I get the object type, but not the values as strings. Here is my code..

Controller

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult GetPerson()
    {
        var _model = _person;
        return Json(_model, JsonRequestBehavior.AllowGet);
    }

    static Person _person = new Person()
    {
        FirstName = "Steve",
        LastName = "Johnson",
        Age = 27
    };  
}

View

@{
Layout = null;
}

<!DOCTYPE html>

<html>
    <head>
        <meta name="viewport" content="width=device-width" />
        <title>Index</title>
        <script src="~/Scripts/jquery-2.0.3.min.js"></script>
    </head>
    <body>
        <div>
            <form>
                <fieldset>
                    <legend>The Person</legend>
                    <label>Name: </label>
                    <input />
                    <label>Age: </label>

                </fieldset>

            </form>
        </div>
    <script type="text/javascript">
        $(document).ready(function() {
            $.ajax({
            url: '/Home/GetPerson',
            type: 'GET',
            success: function (result) { alert(result);}
        });
    });
    </script>

The alert box return [object Object]. I am trying to get the string values of the "Person" object.

Any help would be appreciated.

Thanks!

3 Answers 3

2

you not gone get the data from alert you ddet to specify what variable you trying to alert

 success: function (result) { alert(result.FirstName);}
Sign up to request clarification or add additional context in comments.

Comments

1

success: function (result) { alert(result[0].FirstName);} when returning a json result value you should indecate the index number following with the field name

2 Comments

In his case, result will be an object, not an array.
That way is to get the value of the first Firstname in the result.
1

Try changing alert(result); to alert(JSON.stringify(result); That way you can see the JSON string that's actually being returned.

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.