I want to dynamically choose a partial view depending on what is sent to the controller, and have managed it but I feel that I am a) over complicating it and b) am unsure how to then easily get all page links. Each will be addressed in turn. Please ignore if I make a mistake below, it's from memory! At home it all works, I am after clarification on if there's a better way!
Firstly, what I've done:
I have a controller:
private Dictionary<int, string> pagesForFolder = new Dictionary<int, string>() {
... here I have my list of pages (index and pagename pairs)
}
public ActionResult Test(int id = -1)
{
try {
string pageName = "";
var result = pagesForFolder.TryGetValue(id, out pageName);
if(result)
string directiory = "~Views/folderA/_" + pageName +".cshtml";
return PartialView(directory);
}
catch(Exception ex) { ... }
return View();
}
Then in folderA I have all my partial views for that section of my website. I have many sections and 1 controller per section. However, I am thinking this won't scale out that great as I'll have to keep rebuilding every time I add a page. Would it be better to store the pages in the DB?
I think your current approach is quite reasonable. I think your problem as you mentioned is you have to rebuild your application whenever you add or remove new entry to the dictionary.
As a solution for this you can store your page names in db and retrieve when you needed.
Instead of having a hard coded dictionary try something like this...
In your controller..
public ActionResult Test(int id = -1)
{
try {
string pageName = GetYourPageFromDB(id);
if(!string.IsNullOrEmpty(pageName))
string directiory = "~Views/folderA/_" + pageName +".cshtml";
return PartialView(directory);
}
catch(Exception ex) { ... }
return View();
}
This may not be the exact answer try something like this...
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.