Search code examples
javascript.netasp.net-mvcasp.net-mvc-3razor

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){

           }
        }
      } 
  }
}

Solution

  • 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>