I've just started learning MVC a few days ago and I'm starting to learn the concepts but I'm struggling a bit trying to get a drop down menu on another page. I have a list of categories and I am able to create a drop down box on my Categories\Index.cshtml page. I have the following:
Model:
public class Category
{
public int Id { get; set; }
[Required]
[StringLength(100, MinimumLength = 3)]
public string Name { get; set; }
[Required]
public Boolean Visible { get; set; }
public Category()
{
this.Visible = true;
}
}
Controller:
private DefaultConnection db = new DefaultConnection();
// GET: Categories
public ActionResult Index()
{
var CategoryLst = new List<string>();
var CategoryQry = from c in db.Categories
orderby c.Name
where c.Visible == true
select c.Name;
CategoryLst.AddRange(CategoryQry.Distinct());
ViewBag.Categories1 = new SelectList(CategoryLst);
return View(db.Categories.ToList());
}
Index.cshtml:
Category: @Html.DropDownList("Categories1", "All")
This works as expected - I get a nice drop down box with my visible only Categories. I understand that this works because the user navigated to the "Index" page which is routed to the controller to "Index()" which gets the model and data and then passes that to the page to build the HTML.
What I am having a hard time understanding is how do I get data from the controller/model from a different part of my app? First question, is the controller more tied to the model or the view?
For example, how would I put the above drop down box on my Home\About.cshtml page? I can put the same code above from my Controller into "public ActionResult About()" in my HomeController and then simply put this on the About.cshtml page:
Category: @Html.DropDownList("Categories1", "All")
That works, but I'm guessing it isn't the correct way to do it due to duplicating code.
I'm ultimately trying to add a drop down menu to my nav bar that contains that Category list but I don't understand where to put the code. I'm good with the formatting once I can get the Category name/id list to the page.
Thanks,