Reputation: 616
How to use JavaScript variables inside ASP.NET MVC Razor instructions?
Example:
function updChart(_IndId) {
@foreach (var d in Model.Where(p => p.IndId.Equals(_IndId)))
...
}
I can't use _IndId
variable. Any idea how to use it?
Upvotes: 0
Views: 13912
Reputation: 2098
You can not use Javascript variables in C#, because javascript code is available only after C# / Razor is rendered.
What you can do, is to save the Model in a Javascript array, and then do the foreach loop in Javascript:
var model = [];
@foreach (var item in Model)
{
@:model.push({
@:ID: '@item.ID',
@:Property1: '@item.Property1',
@:Property2: '@item.Property2',
@:Property3: '@item.Property3',
@:});
}
console.log(model);
// here you can filter and do the foreach in Javascript, because your model is available as a Javascript array
Upvotes: 5
Reputation: 6162
You cannot do this. The Razor view is compiled and executed on server and its result is HTML page which is then returned to a client(browser). JavaScript runs in browser and allows you to work with the DOM of HTML page which is already returned from the server.
Upvotes: 2