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?

4

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

So whats my alternative here?
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.