剃刀 - 我可以为视图制作可选模型吗?

时间:2012-04-02 06:07:48

标签: .net asp.net-mvc-3 razor

我第一次使用Razor使用MVC3,我有一个部分视图,在许多其他地方使用并且没有模型。现在我需要它,我可以创建一个可选模型吗?如果它被传递,那么我将使用它,否则我将保留默认行为。

[更新]

我想这样称呼:

@Html.Partial("_myPartialView")

或者这个:

@Html.Partial("_myPartialView", "Some string")

(局部视图模型是一个字符串)

这可能吗?

3 个答案:

答案 0 :(得分:7)

@model FooBar
@if (Model != null)
{
    <div>@Model.SomeProperty</div>
}
else
{
    <div>No model passed</div>
}

更新:

在显示您调用部分内容的方式后,您可以执行以下操作:

@Html.Partial("_myPartialView", null, new ViewDataDictionary())
@Html.Partial("_myPartialView", "Some string")

答案 1 :(得分:1)

使这项工作的另一种方法是不使用@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>

显然,这是一个非常简单的例子,但它说明了如何简单而干净地完成这项工作。 ; - )

答案 2 :(得分:0)

您可以在@Html.Partial("_myPartialView", null)

中传递null

然后在Darin建议的视图中验证模型。

但最好的解决方案imo是将ViewModel对象传递给包含所需字符串属性的视图。你使它可以扩展,并且你没有传入null,你传递一个带有空或空字符串的新ViewModel对象。

相关问题