简体   繁体   中英

adding js code with razor

I am generating some tabs dynamically. I end up with 4 tabs. The class of the tabs is beeing set in the foreach loop, and it is set to be the languageId, as you can see in the code below.

<div id="tabs">
  <ul>
    @for (int i = 0; i < Model.NoteViewModel.NoteTextViewModels.Count(); i++)
    {                                                       
      var languageId = @Model.NoteViewModel.NoteTextViewModels[i].LanguageId;                               
      var imageName = string.Format("FlagSmall_{0}.gif", languageId);
      <li>
        <a href="#@languageId" class="@currentLanguage">
          <img src="@Url.Content("~/Graphics/" + imageName)" />
        </a>
      </li>                                                                                     
    }
  </ul>

Now I introduce a new variable: var currentLanguage = new NotesController().LogonInfo.LanguageId; which holds the current language of the user logged in. What I want to do, is to set focus on the tab where href (or id or class) is the same as the currentLanguage. For this I guess I need js, but since I can't have js code with razor syntax, I'm stuck. So I want something like this:

@for (int i = 0; i < Model.NoteViewModel.NoteTextViewModels.Count(); i++)
{                                                       
  var languageId = @Model.NoteViewModel.NoteTextViewModels[i].LanguageId;
  var currentLanguage = new NotesController().LogonInfo.LanguageId;                                
  var imageName = string.Format("FlagSmall_{0}.gif", languageId);                              
  <li>
    <a href="#@languageId">
      <img src="@Url.Content("~/Graphics/" + imageName)" />
    </a>
  </li>                    
  if (languageId == currentLanguage)
  {
    documentation.getElementById("currentLanguage").focus();
  }
}

How can I achieve this?

I can't have js code with razor syntax

Sure you can, though you may need to explicitly tell the view engine that this is client-side content and not server-side code. You can do this with the <text> tag . It's not an HTML tag per se, but something the razor engine uses to specify static content. Something like this:

<script type="text/javascript">
@for (int i = 0; i < Model.NoteViewModel.NoteTextViewModels.Count(); i++)
{
    <text>
    var someJavaScriptVariable = 'some value';
    // etc.
    </text>
}
</script>

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