简体   繁体   中英

Passing data into PartialView logic

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

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.

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