0

I have a JS function which I want to loop round a c# object passed from the controller. I then want to compare it to a HTML input value - which I have passed into the JS function as a string. Function is called like

searchReleases($("[name=release]").val());


function searchReleases(givenName) {
    var list;
    var data = givenName;
    @foreach (var a in @Model.Releases) {
        if (@a.Name.Contains(givenName)) {
           list+= a.Name + "=";
        }
    }
}

However I can't access the JS variable givenName within the IF statement. I have spent a while trying to find an answer on google but have yet found a workable solution.

Craig
  • 675
  • 1
  • 7
  • 23
  • At compilation time JavaScript doesn't executed. C# code executed at server side and JS code executed at client side. – Konstantin Zadiran Dec 16 '15 at 11:23
  • `@foreach` is razor code which is executed on the server before its sent to the client. `var list` is a client side javascript variable which does not exist at that point. –  Dec 16 '15 at 23:58

2 Answers2

0

You should understand that C# is a server-side code and JS is executed on client-side. So if you generate view in ASP.MVC you have access only to C# data. All information which you want to print on your page will be statically generated to HTML file. Then you can pass this HTML page to browser and inside it, it would be executed JS code. But only based on statically generated data or JS variables.

suvroc
  • 3,058
  • 1
  • 15
  • 29
0

You can't read JS from C#, but you can read C# from JS. So if it's a read-only operation, than convert your C# object to JSON and access it from the JS code.

Try this answer : Asp.net mvc passing a C# object to Javascript

Community
  • 1
  • 1
Gabriel Andrei
  • 187
  • 1
  • 14