1
\$\begingroup\$

I have just started a small MVC application wherein the first task is to display two dropdowns, one with Category and the other with Projects. I have to display the error messages in validation summary if there are any issues with the database. I am not really convinced with the Index method; there could be a better way to handle exception.

Let's say, if the requirements changes later on to add few more dropdowns, then the following would definitely not be the right approach. As an alternate approach, I have to put the Index method logic in the ViewModel, but I am not sure whether that's the correct approach or not.

Could anyone please have a look at the code and suggest better approaches?

public class HomeController : Controller
    {
        private IProjectRepository _projectRepository;

        public HomeController(IProjectRepository projectRepository)
        {
            this._projectRepository = projectRepository;
        }

        public ActionResult Index()
        {
            string err = string.Empty;
            List<string> errors = new List<string>();
            List<Category> category = new List<Category>();         
            var viewModel = new ProjectViewModel();

            if (this._projectRepository.GetCategories(ref category, ref err))
            {
                viewModel.Categories = category;    
            }
            else
            {
                errors.Add(err);
                err = string.Empty;
            }
            List<Project> project = new List<Project>();    
            if (this._projectRepository.GetProjects(ref project, ref err))
            {
                viewModel.Projects = project;
            }
            else
            {
                errors.Add(err);
                err = string.Empty;
            }
            if (errors.Any())
            {
                errors.ForEach(m => ModelState.AddModelError("", m));
                return View(viewModel);
            }
            return View(viewModel);
        }
    }

IProjectRepository.cs

public interface IProjectRepository
    {
        bool GetCategories(ref List<Category> category, ref string strError);

        bool GetProjects(ref List<Project> project, ref string strError);
    }

ProjectRepository.cs

public bool GetCategories(ref List<Category> category, ref string strError)
        {
            SqlDataReader rdr = null;

            using (var conn = new SqlConnection(connectionString))
            {
                SqlCommand com = new SqlCommand("usp_CategoriesGet", conn);
                com.CommandType = CommandType.StoredProcedure;

                try
                {
                    conn.Open();

                    rdr = com.ExecuteReader();

                    if (rdr.HasRows)
                    {
                        while (rdr.Read())
                        {
                            category.Add(new Category()
                            {
                                UniqueId = (int)rdr["UniqueId"],
                                Abbrev = rdr["Abbrev"].ToString(),
                                Name = rdr["Name"].ToString(),
                                Priority = (int)rdr["Priority"]
                            });
                        }
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    strError = ex.Message;
                    conn.Close();
                    return false;
                }               
            }
        }

        public bool GetProjects(ref List<Project> project, ref string strError)
        {
            SqlDataReader rdr = null;

            using (var conn = new SqlConnection(connectionString))
            {
                SqlCommand com = new SqlCommand("usp_ProjectsGet", conn);
                com.CommandType = CommandType.StoredProcedure;

                try
                {
                    conn.Open();

                    rdr = com.ExecuteReader();

                    if (rdr.HasRows)
                    {
                        while (rdr.Read())
                        {
                            project.Add(new Project()
                            {
                                Title = rdr["Title"].ToString(),
                                Description = rdr["Description"].ToString()
                            });
                        }
                    }
                    return true;
                }
                catch (Exception ex)
                {
                    strError = ex.Message;
                    conn.Close();
                    return false;
                }               
            }
        }

ProjectViewModel.cs

public class ProjectViewModel
    {
        public List<Project> Projects{ get; set; }

        public List<Category> Categories { get; set; }      
    }

Alternate approach:

Index method:

public ActionResult Index()
    {
        string err = string.Empty;
        List<string> errors = new List<string>();
        List<Category> category = new List<Category>();

        var viewModel = ProjectViewModel.CreateViewModel();

        if (viewModel.errors.Any())
        {
            viewModel.errors.ForEach(m => ModelState.AddModelError("", m));
        }

        return View(viewModel);
    }
[HttpPost]
        public ActionResult Index(ProjectViewModel viewModel)
        {

            return View(viewModel);
        }

ViewModel

 public class ProjectViewModel
    {
        public List<string> errors { get; set; }

        public List<Category> Categories { get; set; }

        public int SelectedCategory { get; set; }

        public List<Project> Projects { get; set; }



        public static ProjectViewModel CreateViewModel()
        {
            var projectViewModel = new ProjectViewModel();

            string err = string.Empty;
            List<Category> categoryList = new List<Category>();
            List<Project> projectList = new List<Project>();
            projectViewModel.errors = new List<string>();

            ProjectRepository rep = new ProjectRepository();

            if (rep.GetCategories(ref categoryList, ref err))
            {
                projectViewModel.Categories = categoryList;
            }
            else
            {
                projectViewModel.errors.Add(err);
                err = string.Empty;
            }
            if (rep.GetProjects(ref projectList, ref err))
            {
                projectViewModel.Projects = projectList;
            }
            else
            {
                projectViewModel.errors.Add(err);
            }
            return projectViewModel;

        }
    }
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.