0

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?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Richasantos
  • 576
  • 2
  • 8
  • 15

2 Answers2

5

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
Enrique Zavaleta
  • 2,098
  • 3
  • 21
  • 29
2

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.

Alexey Andrushkevich
  • 5,992
  • 2
  • 34
  • 49
  • 1
    So whats my alternative here? – Richasantos Oct 06 '16 at 16:03
  • If you need to partially update something on your page you have to make AJAX request to the server, get data and apply it to a specific part of your page. – Alexey Andrushkevich Oct 06 '16 at 16:08
  • Razor is a generic templating engine and *could* be adapted to return JavaScript. I see this as an area that will probably be addressed in the future. I suppose there's nothing stopping you from creating an MVC endpoint that pre-processes the JavaScript files. – mark gamache Feb 20 '17 at 16:04