user1603179
user1603179

Reputation: 87

Razor View Engine: Complex looping with JS

Hi I am wondering how do I add javascript if condition inside in nested foreach loop expamle:

function validation(){
  @foreach (var region in Model.DefaultDeliver)
  {
  //js code
  if(document.getElementByName('#@( region.Region.RegionName)') != null){ 
      foreach (var country in region.Region.Countries)
       {    
          //js code      
          if(document.getElementByName('#@(region.Region.RegionName)') != null){

           }
        }
      } 
  }
}

Upvotes: 1

Views: 145

Answers (1)

dove
dove

Reputation: 20674

Place the @ before

@foreach (var country in region.Region.Countries)

If there is compiling confusion between the razor and js you can escape the javascript with

@: (note colon) for one line

//js code    
@:if(document.getElementByName('#@( region.Region.RegionName)') != null){ 

or wrap several with text node

@foreach (var country in region.Region.Countries)
    <text>
        if(document.getElementByName('#@(region.Region.RegionName)') != null){

           }

    </text>

Upvotes: 2

Related Questions