Can`t get json object to with knockout

2019-07-25 13:34发布

I can`t get json object.

My object is:

public class Person
{
   public string firstName { get; set; }
   public string lastName { get; set; }        
}

PersonsControll:

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

    // GET: /Persons/GetPerson
    //[AcceptVerbs(HttpVerbs.Get)]
    //[OutputCache(Duration = 0, VaryByParam = "*")]
    public JsonResult GetPerson()
    {
        Person p = new Person { firstName = "Jonas", lastName = "Antanaitis" };
        return Json(p, JsonRequestBehavior.AllowGet);
    }

My index view:

@Scripts.Render("~/bundles/knockout")

<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>

<div id="dispJson"></div>
<script type="text/javascript">                
    var data = $.getJSON(".../GetPerson", function (result) {
        //state = result.readyState;
        firstName: result.firsName;
        lastName: result.lastName;
    })    
    .error(function () { alert("error"); });    

    function viewModel() {
        ko.mapping.fromJS(data);
        //state = data.readyState;
        //firstName = data.firstName;
        //lastName = data.lastName;
    };    
    document.write(JSON.stringify(data)); //this line prints  "{"readyState":1}"

    ko.applyBindings(new viewModel());    
</script>

When I go to ".../GetPerson" in browser, I get this displayed: {"firstName":"Jonas","lastName":"Antanaitis"}

,but when try to get data witch javascript in view - I dont`t get this data.

What I am doing wrong, why I cant get data? Where commented code - I tried this approaches.. but nothing helped.

I tried:

*$.ajax({
    type: "GET",
    cache: false,
    url: ".../GetPerson",        
}).done(function (msg) {
    alert("Data Saved: " + msg.readyState + "  " + msg.firstName + "  " + msg.lastName);
});*

Then alert box displays: "Data Saved: undefined Jonas Antanaitis"

1条回答
贪生不怕死
2楼-- · 2019-07-25 13:59

You are mixing async code with sync code... You have this line here

var data = $.getJSON(".../GetPerson", function (result) {

data will actually be the a promise (this is what the ajax returns). You do not actually have the data until the callback executes - ie result is the thing that has the ACTUAL data.

You need to move the binding to INSIDE the callback OR use an observable that you set after the fact:

1) Inside the callback example

<script type="text/javascript">                
    $.getJSON(".../GetPerson", function (result) {

        function viewModel() {
            return ko.mapping.fromJS(result);
        };

        ko.applyBindings(new viewModel());
    })    
    .error(function () { alert("error"); });        
</script>

2) Use an observable

<script>
    function viewModel() {
        return { data: ko.observable() };
    };

    // Your html bindings will bind to data.* instead of just *
    ko.applyBindings(new viewModel());

    $.getJSON(".../GetPerson", function (result) {
        data(ko.mapping.fromJS(result));
    })    
    .error(function () { alert("error"); });      
</script>

And the corresponding html (The with binding makes it a bit cleaner than if):

<!-- ko with: data -->
<p>First name: <strong data-bind="text: firstName"></strong></p>
<p>Last name: <strong data-bind="text: lastName"></strong></p>
<!-- /ko -->

The advantage of the second method is that you are binding everything quickly... and can then show your data as it comes in.

查看更多
登录 后发表回答