实现这项工作的另一种方法是不使用 @model 指令限制模型的类型。然后,您可以将自己的变量用于可能传入局部视图的不同类型的模型(在对 @Html.Partial 的调用中显式设置或仅从包含视图继承)。
假设您网站的用户是员工或客户,并且您有一些局部视图来显示一些应该有效的信息,无论他们如何登录(或者即使他们没有登录)。您的模型如下所示:
public class Employee
{
public virtual int ID { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public string GetPrimaryRole() { /* Fetch the name of the primary Role from Roles */ }
// A bunch of other stuff...
}
public class Customer
{
public virtual int ID { get; set; }
public virtual string FullName { get; set; }
public virtual int RewardsPoints { get; set; }
// A bunch of other stuff...
}
如你所见,信息是相似的,但是将这两个东西抽象成一个通用接口真的很困难。在局部视图的顶部,您可以放置如下内容:
@{
var employee = Model as Employee;
var customer = Model as Customer;
string message = "Welcome, Guest!"; //This is displayed if they aren't logged in
if (employee != null)
{
message = string.Format("Welcome, {0} {1}, {2}!",
employee.FirstName, employee.LastName, employee.GetPrimaryRole());
}
else if (customer != null)
{
message = string.Format("Welcome, {0}! You have {1} points!",
customer.FullName, customer.RewardsPoints);
}
}
<div>@message</div>
显然,这是一个非常简单的示例,但它说明了如何简单而干净地完成此操作。 ;-)