I would ask also for best practices and patterns for asp.net MVC, using this example:
I have a project. This is its architecture:
- Models
- Controler
- Views
- Tools
In models folder I have every single ViewModel in separate class field. All of table declarations (objects) I put in one file (AccountModels.cs or ForumModels.cs). I have a separate file for EF context (MyAppContext.cs).
Controler - here I have only Controler classes. But maybe part of code will be better example and suggestion what can I improve:
private AppContext db = new AppContext ();
[HttpPost]
[Authorize]
public ActionResult AddGun(GunModel model)
{
if (ModelState.IsValid)
{
Gun gunToAdd = new Gun
{
Tilte = model.Tilte,
AuthorID = UserTools.getUser(User.Identity.Name).UserId,
AddDate = DateTime.UtcNow,
Content = model.Content,
CategoryID = model.CategoryID,
CategoryName = GunsTools.getCategoryName(model.CategoryID)
};
db.Guns.Add(gunToAdd);
db.SaveChanges();
return RedirectToAction("Details", new { ID = gunToAdd.ID });
}
return RedirectToAction("Index");
}
This is a part of controler with AddGun Action. Others ActionResults are similar - generaly I use lambda expression on my db context to get values etc.
Views - Views in separate folder, for Partial Views I set special prefix (for example - _NavigationPartial.cshtml or _CalculatorPartial.cshtml). Is there anything for improve here? Of course Views use ViewModels, not Models.
And at least - Tools. I've put here some classes and methods to prevent from repeating code. Here is some methods witch returns from database some objects or just strings, like GetUser(..) or GetCategoryName(..). Is it a good practise at all?
I think that many young MVC developers have the same project architecture (I personally saw it in a few companies) and many of them perhaps also wants to improve something in theirs projects to be a better programmers.
Regards