【问题标题】:Multiple view models in Razor viewRazor 视图中的多个视图模型
【发布时间】:2016-10-27 14:16:51
【问题描述】:

剃刀视图处理多个模型的最佳方式是什么?对于 MVC3 应用程序。

我有两个相似的模型,但是邮政编码字段是一个模型所必需的,而另一个则不需要

public class IrelandPostcodeLookupViewModel , IWithProgress
{
    readonly Progress _Progress = new Progress(Step.Delivery);

    public Progress Progress
    {
        get { return _Progress; }
    }

    [Required(ErrorMessage = "Please enter your house number or name")]
    [DisplayName("House number or name")]
    public string HouseNumber { get; set; }

    [StringLengthWithGenericMessage(50)]
    [DisplayName("Eircode")]
    public string Postcode { get; set; }

}

public class PostcodeLookupViewModel , IWithProgress
{
    readonly Progress _Progress = new Progress(Step.Delivery);

    public Progress Progress
    {
        get { return _Progress; }
    }

    [Required(ErrorMessage = "Please enter your house number or name")]
    [DisplayName("House number or name")]
    public string HouseNumber { get; set; }

    [StringLengthWithGenericMessage(50)]
    [Required(ErrorMessage = "Please enter your postcode")]
    [DisplayName("PostCode")]
    public string Postcode { get; set; }

}

在控制器中,我想根据我通过的国家/地区使用特定的视图模型。类似的东西

public virtual ActionResult PostcodeLookup(string country)
{
    if (country == Country.UnitedKingdom)
         return View(new PostcodeLookupViewModel());
    else
         return View(new IrelandPostcodeLookupViewModel());
}

我在视图中处理这个问题

@model dynamic

我遇到的问题是我的视图包含部分视图

@Html.Partial("~/Views/Shared/_Progress.cshtml", Model.Progress)

我遇到了错误“HtmlHelper”没有名为“Partial”的适用方法,但似乎有一个名为“Partial”的扩展方法。扩展方法不能动态调度'

谁能告诉我如何处理部分视图?

谢谢

【问题讨论】:

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


    【解决方案1】:

    因为Modeldynamic,所以Model.Progress 也会产生dynamic
    对于 dynamic 对象上的所有属性和函数调用都是如此,无论您走多远。

    要解决这个问题,您可以对Model.Progress 对象进行类型转换:

    @Html.Partial("~/Views/Shared/_Progress.cshtml", (Progress)Model.Progress)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 2017-01-15
      • 2016-01-21
      • 1970-01-01
      相关资源
      最近更新 更多