I am building a Book Store website with ASP.NET MVC 5, Razor, EntityFramework My entities
Category {
int CateID,
string CateName
}
Book {
int BookID,
int BookName
}
My _Layout.cshtml have a sidebar (left menu), which display all of categories from database (same for all page). I have two Controller: HomeController and BookController, all the views of these controls will use the above layout template. I thought about UserControl, I create a UserControl name SideBarUserControl
@model List<Category>
@if (ModelCount > 0)
{
<ul>
foreach (var l in Model)
{
<li><a href="">@l.CateName</a></li>
}
</ul>
}
And in the Home/Index's view:
@Html.Partial("_SideBarUserControl")
But I don't know exactly where to put the binding code for it. Does it useful if I have a BaseController, which HomeController and BookController extended from it.
Since you are preforming DB calls in the _Layout.cshtml
then I would suggest to use Ajax to get the data?
In your _Layout
create a Ajax call to something on any controller, I would personally put it into the HomeController.cs
but that is my own preference.
Then from the result of that call render the data in your Partial view.
This way you are not having to wait for any DB calls to finish, the downside is that the sidebar will not appear at the exact same time as your DOM loads. But you could always make it more friendly looking by using something like Spin.js
Action Method
[HttpPost]
public ActionResult GetCategories()
{
//Code to fetch the data for the partial
return PartialView("_SideBarUserControl", model);
}
Ajax Example
$(function () {
$.ajax({
type: "POST",
url: '@Url.Action("GetCategories","Home")',
success: function (data) {
var result = data;
$('targetLocation').html(result);
}
});
});