Home Adding a dropdown list outside or RenderBody call
Reply: 1

Adding a dropdown list outside or RenderBody call

ska-dev
1#
ska-dev Published in 2017-12-04 14:29:06Z

I have a .NET MVC project with Razor views and I would like to implement search functionality that consists of a dropdown list, a text box and a search button.

The problem is that I would like to implement this search snippet in my _Layout.cshtml file outside of the @RenderBody() call. This means that the search functionality would be accessible on every page (it would be located at the very top right corner).

I'm trying to find out what is a good way of implementing this. I can get it to work but it would involve adding same code (do get dropdown values) to all controllers and actions.

ViewBag.States = new SelectList(db.States, "Id", "Name");

Is there a better way to implement this? It feels very repetitive to do it this way.

Shyju
2#
Shyju Reply to 2017-12-04 14:39:36Z

You can have a child action method which returns the partial view needed for your header and call this action method in your layout.

Create a view model for the properties needed.

public class AllPageVm
{
    public int SelectedItem { set; get; }
    public List<SelectListItem> Items { set; get; }
}

Now create an action method in any of your controller. Mark this action method with ChildActionOnly decorator.

public class HomeController : Controller
{
    [ChildActionOnly]
    public ActionResult HeaderSearch()
    {
        var vm = new AllPageVm()
        {
            Items = db.States
                      .Select(a => new SelectListItem() {Value = a.Id.ToString(),
                                                         Text = a.Name})
                     .ToList()
        };
        return PartialView(vm);
    }

Now in the HeaderSearch.cshtml partial view, you can render whatever markup you want for your search header. Here is a simple example to render the dropdown. You may update this part to include whatever markup you want (Ex : a form tag which has textbox, dropdown and the button etc)

@model AllPageVm
<div>
    <label>Select one state</label>
    @Html.DropDownListFor(a => a.SelectedItem, Model.Items, "Select")
</div>

Now in your layout, you can call this child action method

<div class="container body-content">
    @Html.Action("HeaderSearch", "Home")
    @RenderBody()
    <hr/>
    <footer>
        <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
    </footer>
</div>

Make sure you are calling PartialView method from the HeaderSearch child action method instead of View method. If you call View method, it will recursively call the same method and you will get a StackOverflow exception

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.342494 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO