Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question

3 Answers 3

up vote 2 down vote accepted

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

 success: function (result) { alert(result.FirstName);}
share|improve this answer

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

share|improve this answer

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

share|improve this answer
    
In his case, result will be an object, not an array. –  Mahesh Sep 6 '13 at 3:41
    
That way is to get the value of the first Firstname in the result. –  Don Sep 6 '13 at 4:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.