Reputation: 49
i have got a javascript array which array retrieve from rest. I want to populate this array result in razor foreach. But i couldnt reach to my global array result in javascript. How can i do this ?
Here is my javascript;
function getAlarmModels(cb) {
$.ajax({
url: "SomeURL",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: failureCb,
success: successCb,
timeout: 60000
});
function failureCb(jqXHR, textStatus, errorThrown) {
var errorCode = jqXHR.status;
var errorText = textStatus;
console.log("Error Code [" + errorCode + "]: " + errorText);
if (cb)
cb(null);
}
function successCb(data) {
window.PreviousBill = JSON.parse(data);
if (cb)
cb(JSON.parse(data));
}
}
Here is razor;
@for (int i = 0; i <window.PreviousBill.Count ; i++)
{
}
}
How can i access to "window.PreviousBill" ?
Upvotes: 1
Views: 248
Reputation: 9463
You can not use Razor to render data received through AJAX. The reason is the page life cycle:
1) Controller action handles a request and returns a View.
2) View is rendered with Razor on the server side, the resulting HTML is delivered to the client.
3) Client receives the HTML and executes any embedded JavaScript on the client side. This includes any AJAX calls.
As you can see, at the time your JS code runs, any Razor syntax has been long converted to HTML. On the other hand, at the time Razor renders the View, no JS variables are available yet.
What you can do:
Upvotes: 1