Brian Evans
Brian Evans

Reputation: 235

call JavaScript function inside razor foreach statement

I have looked through several posts but have not found an answer that actually solves this issue so I am asking whilst trying to provide the most pertinent details.

I have a very simple script file called custom.js ...

function AddListItemToUnorderedList(pageCode, menuName) {
    $('.child_nav').append('<li><a href="' + pageCode + '"><span>' + menuName + '</span></a></li>');
} 

I have made reference to that script in my partial page.

<script type="text/javascript" src="~/Scripts/custom.js"></script>

@{
   Layout = null;
 }

 <ul class="child_nav" style="display: none;"></ul>

 @foreach (var item in ViewBag.MenuItems)
 {
     @Html.Raw("<script type='text/javascript'>")
     @Html.Raw("AddListItemToUnorderedList('")
     @item.PageCode
     @Html.Raw("', '")
     @item.MenuName
     @Html.Raw("');")
     @Html.Raw("</script>")
 }

The above code works but it looks terrible AND it adds a script tag to the markup for each item in the MenuItems collection. The MenuItems collection simply contains a list of two strings correlating to my menu's display name and html link....consider this to be populated with something as simple as Test Page for the name and myTestPage.com for the link.

I have see some shortcut syntax like this

@: AddListItemToUnorderedList(item.PageCode, item.MenuName)

however, I am not able to get that to work no matter what I try.

Any clear suggestions that work that will allow me to make a direct call to the JavaScript function passing in the two properties from the ViewBag where I don't have to create the script tags and use @Html.Raw?

Upvotes: 0

Views: 11439

Answers (1)

Eric G
Eric G

Reputation: 2617

Something like the below should work. Pull out the script tags from the foreach, and then reference the javascript. You'll also have to put <text></text> tags around the javascript and quotes around the variables so they will transfer correctly:

<script type='text/javascript'> 
@foreach (var item in ViewBag.MenuItems)
{
    <text>AddListItemToUnorderedList('@item.PageCode', '@item.MenuName')</text>
}
</script>

Upvotes: 4

Related Questions