Razor - 我能为视图创建可选模型吗?

5
我是第一次使用MVC3和Razor,我有一个被多个页面引用的局部视图,这个视图没有模型。现在我需要它,我是否可以创建一个可选的模型?如果传递了模型,则使用传递的模型,否则使用默认行为。
[更新]
我希望像这样调用它:
@Html.Partial("_myPartialView")

或者这个:
@Html.Partial("_myPartialView", "Some string")

部分视图模型是一个字符串。

这个可能吗?

3个回答

9
@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")

当没有传递模型时,我会收到以下错误:`@Html.Partial("_myPartialView")`字典中传递的模型项类型为 'ModelOfTheContainerView',但该字典需要一个类型为 'PartialViewModel' 的模型项。 - kerzek
@kerzek,我已经更新了我的答案,向您展示了如何在不出现异常的情况下调用带有空模型的部分视图。您需要使用helper的第三个参数,并传递一个新的ViewDataDictionary,以避免将父模型传递给部分视图。 - Darin Dimitrov
谢谢。你说得对,如果我用两个参数调用它,那么就会使用父级的模型。我想我别无选择,只能将所有调用都改为使用 string.empty 了。 - kerzek
是的,这就是 Html.Partial 助手函数的工作原理。如果您未显式指定不为空的其他模型,它将使用父模型。 - Darin Dimitrov

2
另一种使此方法生效的方式是不使用@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>

显然,这只是一个非常简单的例子,但它说明了如何简单而清晰地完成此操作。;-)

0

@Html.Partial("_myPartialView", null)中可以传递null。

然后像Darin建议的那样,在视图中验证模型。

但是,在我看来,最好的解决方案是将一个ViewModel对象传递到您的视图中,其中包含您需要的字符串属性。这使其具有可扩展性,并且不会传递null,而是传递一个新的ViewModel对象,其中包含一个空或null字符串。


我已经尝试过,但如果我将第二个参数设置为null进行调用,则部分会继承父级的模型。我需要第三个参数,或者在这种情况下,一个string.empty。 - kerzek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接