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"
You are mixing async code with sync code... You have this line here
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
2) Use an observable
And the corresponding html (The with binding makes it a bit cleaner than if):
The advantage of the second method is that you are binding everything quickly... and can then show your data as it comes in.