I am developing an MVC application using a mysql database.
I searched a lot through SO and other sites about the architecture/structure. I found a lot of similar questions but I am still in doubt.
In my applications there is a categories section; the structure is shown below:
View:
Category – (views in category folder listed below)
CreateCategory
DeleteCategory
ManageCategory
Controller:
CategoryController – (action names listed below)
CreateCategory
DeleteCategory
ManageCategory
Model: This is where I have doubts. I have a model named CategoryModels but I don’t know if I doing things the right way or not. I don’t know where I should put the service functions – for example where I put functions to create or delete categories.
What I did is create a CategoryServices class inside CategoryModel.cs and write functions inside that. DAL file is put in app code folder, so to access the DB the function will create an object of DAL and call it. Is this the right way?
In CategoryModels.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Mvc;
using System.Web.Caching;
namespace TraktorumMVC.Models
{
public class CategoryModels // contain properties for the 3 views (CreateCategory,DeleteCategory and ManageCategory
{
public IEnumerable<SelectListItem> CategoryList { get; set; }
public IEnumerable<SelectListItem> AvailableCategories { get; set; }
//etc..........
}
public class CategoryServices // this class contain all service functions related to categories
{
public int RemoveCategory(int categoryId) // this will remove a category
{
int status = -1;
try
{
string query = Resources.Queries.RemoveCategory;
DAL objDAL = new DAL(); //DAL file is in Appcode folder. IS this right way
string[] inParamNameArray = { "Id"};
string[] inParamValueArray = { categoryId.ToString()};
object[] inParamTypeArray = { DbType.Int32 };
status =Convert.ToInt32( objDAL.ExecuteScalar(query, inParamNameArray, inParamValueArray, inParamTypeArray, true));
}
catch (Exception ex)
{
DeveloperLog.WriteExceptionLog(ex, "CategoryServices.RemoveCategory");
}
return status;
}
public bool InsertCategory(int parentCategoryId, string icon, string name)
{
//bla bla
}
}
}
Is this right way to do this? Did this break the model concept?
The “Model” in ASP.NET MVC is not very prescriptive, and is certainly less prescriptive than the Views or Controllers.
That said, there isn’t necessarily a right or wrong way to do your model, but there are a few popular/common approaches that people take:
In your situation, if you can, I’d recommend putting in an ORM to handle the persistence of categories. If your current DAL is doing more than just persistence, then I’d recommend you separate it out to a service, with corresponding interface, that your controller can get a reference to and use to drive your application forward.