Search code examples
c#asp.net-mvcrazorviewbag

ASP MVC - ViewBag from partial to view


i need set property of ViewBag in partial view and call in view. Here is my code: This is index.cshtml:

<h2>@ViewBag.Title</h2>
Html.RenderPartial("~/Views/Article/Partial.cshtml");

And this controller:

public ActionResult Index(int id)
{
  return View(_db.Articles.Find(id));
}

This is Partial.cshtml:

@model Article
@{
    ViewBag.Title = Model.Article.Title;
}

<h2>....</h2>
//html...

Solution

  • Based on the code you provided above, you seem to be setting the ViewBag.Title in the partial view, and attempting to use it in the Index view. This won't work. You also seem to be wanting to write the article's title, which in a partial, wouldn't modify the page title.

    You should consider where you want to set the Title; either in the controller action or in the primary view. Here's an example:

    Controller

    public ActionResult Index(int id)
    {
         ViewBag.Title = "My Title";
         return View(_db.Articles.Find(id));
    }
    

    Modify your Index.cshtml file:

    Index.cshtml

    @model Article
    
    <h2>@ViewBag.Title</h2>
    @Html.Partial("_Partial", Model)
    

    And then update the partial. Note, that the Razor engine is smart enough to figure out which cshtml file to use, so you don't need to give it the full path. A general naming convention is to start partials with an underscore.

    _Partial.cshtml

    @model Article
    
    <h2>@Model.Title</h2>
    ...
    

    I don't quite know how your model is set up, so you may want to change that. You should also consider why you're opting to use a partial instead of just building everything into the index file.

    If the idea is the page should just show an individual article (which the Linq query seems to imply), you could just build it all on a single view. Here's an example:

    Proposed Index.cshtml

    @{
        ViewBag.Title = Model.Title;
    }
    
    @model Article
    
    <h2>@Model.Title</h2>
    <p>@Model.Content<p>
    

    This is just a sample, of course, and you should apply your formatting as you want. This will set the page title (in the browser) to "Site Name - Article Title", and show the title in the h2 element as well.