First things first, if your already in a code block, you do not want @ toggles except when directly rendering to the browser.
Secondly, you're calling a foreach loop on precisely the same collection in your submenu. That's likely not what you meant to do.
You also want to apply an id as a unique element in HTML, you're using it as if it were a class, multiple instances of the same id in the same document: this will break jQuery. Better to apply classes to your tags instead.
If you have a collection of parent and children nodes just thrown together as well, that's not the best data access scheme. Anyway, here's a corrected version of your Razor, which should do what it looks like you're trying to do:
@if (ViewBag.categories != null)
{ <ul id="category">
@foreach (var category in ViewBag.categories)
{
if (category.ParentID == null)
{
<li class="categoryli">
@category.Name
<ul class="submenu">
@foreach (var subcategory in category.categories)
{
if (category.CategoryID == subcategory.ParentID)
{
<li>
@subcategory.Name
</li>
}
}
</ul>
</li>
}
}
</ul>
}
If ParentID is an it you'll need to do if(category.ParentID == 0)
Now you'll need to modify your jQuery:
$(function () {
$('.submenu').hide();
$('.category >li').click(function () {
$(this).children('.submenu').slideToggle('slow');
});
});
And finally, I would remove the submenu css, or at least remove the display:none; from it.