我有两个与在 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;
}
}
}
}
它工作得很好,但我的问题是:我是否使用了最好的方法?