简体   繁体   中英

Use JavaScript Variable in Asp.net MVC Razor syntax

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM