문제

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!

도움이 되었습니까?

해결책

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

 success: function (result) { alert(result.FirstName);}

다른 팁

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

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top