ASP.NET MVC中的最佳实践模型

G10*_*G10 3 c# model-view-controller asp.net-mvc

我有两个问题与在mvc项目中管理模型的最佳方法有关.

  • 我可以使用构造函数初始化我的模型(显然与其相关的逻辑)?
  • 为此,最好使用"构造方式",或者我应该在创建新模型实例后使用控制器调用的扩展方法?

例如,我有一个联系表格的模型.用户可以有三个角色:匿名,客户或供应商,他可以在每个州提交表格.我唯一想要的是,如果用户登录(如客户角色或供应商的角色),我想在文本框中预加载他的数据.为此,我写了这段代码:

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;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它工作得很好,但我的问题是:我使用最好的方式吗?

jru*_*ell 5

不,您不应该依赖于HttpContext模型中的数据访问或任何数据访问.你正在通过模型绑定(更不用说紧耦合)来解决各种问题.

在Controller中设置模型属性,或者在Controller使用的存储库中设置模型属性.

public ActionResult Contact(string id)
{
   var client = _repository.GetClient(id);
   var model = new RequestModel(){ /* set your properties from client */ };

   return View(model);
}
Run Code Online (Sandbox Code Playgroud)