0

I was following a tutorial in a book on creating a categories side menu using a partial view. It went fine until it got to the feature of showing the currently selected category.

The problem arises as there doesn't seem to be any logic in passing the currently selected category to the partial view.

The layout CSHTML file has for displaying categories

@{ Html.RenderAction("Menu", "Nav"); } 

as you can see the selected category ID is not being passed

if you look at the NavController the menu method accepts a select category ID

 public PartialViewResult Menu(int selCatID = -1) { ViewBag.SelectedCatID = selCatID; return PartialView(repository.Categories); } 

But the call from the layout.html file seems to be calling the Menu without a parameter causing the selCatID to always be -1

Here is the view for Menu

 @foreach (var cat in Model) { @Html.RouteLink( cat.CategoryName , new { controller = "Company", action="List" , catID=cat.ID, page= 1}, new { @class = cat.ID == ViewBag.SelectedCatID ? "selected" : null } ) } 

There doesn't seem to be any visible code that shows the selected CatID from the main controller (Company) being passed into the view for NavController.

I figured that the main controller should be setting the viewbag for the selected ID.I did the following changed, and it worked but I am not sure if it is the correct technique. I was wondering if I am doing it correctly or have I missed out something?.

in the layout file pass a parameter in:

Html.RenderAction("Menu", "Nav", new { selCatID = ViewBag.SelCatID }); 

in the main entity controller (CompanyController) set the viewbag of the current selected ID

public class CompanyController : Controller { ..... public ViewResult List(int catID = -1, int page = 1) { CompaniesListViewModel viewModel = new CompaniesListViewModel { ........... }; ViewBag.SelectedCatID = catID; return View(viewModel); 
2
  • Why is the Action receiving catID as -1? Commented Jul 15, 2012 at 21:04
  • TravisJ i fixed the typo when entering here, the book was using this formatting, I usually avoid using it, for this very reason. Andre - the -1 is there so catID is an optional parameter, -1 indicates no category was selected Commented Jul 15, 2012 at 22:03

1 Answer 1

1

The problems was this code

 Html.RenderAction("Menu", "Nav", new { selCatID = ViewBag.SelCatID }); 

I had added the parameter in as without it was passing in a null value and crashing it on the first run. So I changed it back to: Html.RenderAction("Menu", "Nav");

To handle the null, I changed the parameter to a nullable int

 public PartialViewResult Menu(int? selCatID = -1) { ViewBag.SelectedCatID = selCatID; 

And now all is working.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.