Model best practices in ASP.NET MVC
asp.net-mvc, c#, model-view-controller
Solution
No, you should not have a dependency on `HttpContext` or any data access in your models. You're opening yourself up to all kinds of problems with model binding (not to mention tightly coupled).
Set your model properties in your Controller, or a repository that is used by your Controller.
public ActionResult Contact(string id)
{
var client = _repository.GetClient(id);
var model = new RequestModel(){ /* set your properties from client */ };
return View(model);
}
Problem
I've got two questions related to the best way to manage a model in an mvc project. - Can i use a constructor for initialize my model (obviously with its related logic)? - For this purpose, is better to use "the constructor way", or I should use extension method called by controller after the creation of the new model instance? For example I've a model for a contact form. User can be in three roles: anonymous, client or supplier and he can submit the form in each state. The only thing that I want is that if the user is logged in (like client's role or supplier's role) I want to preload in textboxes his datas. For do this I've wrote this code: ``` using System; using System.Web; using System.Web.Security; using DrOkR2.Bll.Managers; namespace DrOkR2.WebFront.Models { public class RequestModel { public string FirstName { get; set; } public string LastName { get; set; } public string Phone { get; set; } public string Email { get; set; } public string Prov { get; set; } public string Request { get; set; } public bool UsageConditions { get; set; } public RequestModel() { if (!HttpContext.Current.User.Identity.IsAuthenticated) return; if (HttpContext.Current.User.IsInRole("Client")) { var guid = (Guid)Membership.GetUser().ProviderUserKey; var manager = new ClientManager(); var client = manager.GetClient(guid); client.Email = Membership.GetUser().Email; FirstName = client.FirstName; LastName = client.LastName; Email = client.Email; Phone = client.Phone; Prov = client.Prov; } else if (HttpContext.Current.User.IsInRole("Supplier")) { var guid = (Guid)Membership.GetUser().ProviderUserKey; var manager = new SupplierManager(); var supplier = manager.GetSupplier(guid); supplier.Email = Membership.GetUser().Email; FirstName = supplier.FirstName; LastName = supplier.LastName; Email = supplier.Email; Phone = supplier.PrimaryPhone; Prov = supplier.BusinessProv; } } } } ``` It works perfectly, but my question is: am I using the best possible way?