【问题标题】:MVC3 partial view with ViewModel property as model以 ViewModel 属性作为模型的 MVC3 局部视图
【发布时间】:2012-02-25 04:36:20
【问题描述】:

我正在尝试将 ViewModel 属性传递给局部视图,但出现以下错误: “传入字典的模型项的类型为'f__AnonymousType2`1[DomaniOnline.Models.DomaniData.TempRates]',但此字典需要'DomaniOnline.Models.DomaniData.TempRates'类型的模型项。”

如何传递 VM 属性使其不是匿名类型?

观点:

@model DomaniOnline.Models.ViewModels.CompareRatesViewModel

@{
ViewBag.Title = "Rate Comparison";
}

<h2>Compare Rates</h2>

<table>
<tr>
    <td>@Html.DisplayTextFor(m=>m.TempRate1.CarrierName)</td>
    <td>@Html.DisplayTextFor(m=>m.TempRate2.CarrierName)</td>
    <td>@Html.DisplayTextFor(m=>m.TempRate3.CarrierName)</td>
    <td>@Html.DisplayTextFor(m=>m.TempRate4.CarrierName)</td>
</tr>
<tr>
    <td>@Html.Partial("_TempRatesPartial", new { tempRate = Model.TempRate1 })</td>
    <td>@Html.Partial("_TempRatesPartial", new { tempRate = Model.TempRate2 })</td>
    <td>@Html.Partial("_TempRatesPartial", new { tempRate = Model.TempRate3 })</td>
    <td>@Html.Partial("_TempRatesPartial", new { tempRate = Model.TempRate4 })</td>
</tr>
</table>

局部视图:

@model DomaniOnline.Models.DomaniData.TempRates

<fieldset>
   <legend>TempRates</legend>

   <div class="display-label">Carrier Name</div>
   <div class="display-field">
      @Html.DisplayFor(model => model.CarrierName)
   </div>
....
</fieldset>

还有 ViewModel:

 public class CompareRatesViewModel
 {
    public TempRates TempRate1 { get; set; }
    public TempRates TempRate2 { get; set; }
    public TempRates TempRate3 { get; set; }
    public TempRates TempRate4 { get; set; }
    public TempRates TempRate5 { get; set; }

    public CompareRatesViewModel(IEnumerable<TempRates> TempRateList)
    {
        this.TempRate1 = TempRateList[0];
        this.TempRate2 = TempRateList[1];
        this.TempRate3 = TempRateList[2];
        this.TempRate4 = TempRateList[3];
        this.TempRate5 = TempRateList[4];
    }

 }

【问题讨论】:

    标签: asp.net-mvc-3


    【解决方案1】:

    为什么不直接传入对象而不是使用匿名类型呢? 您的部分采用 TempRates 并且您的 TempRate1 是 TempRate 类型,因此您应该能够在不强制转换的情况下执行此操作。

    <td>@Html.Partial("_TempRatesPartial", Model.TempRate1)</td>
    

    【讨论】:

      【解决方案2】:

      您需要将匿名类型转换为部分视图的模型类型:

      @Html.Partial("_TempRatesPartial", (DomaniOnline.Models.DomaniData.TempRates)Model.TempRate1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-11
        • 1970-01-01
        • 1970-01-01
        • 2011-07-26
        • 1970-01-01
        • 2014-06-27
        • 2012-11-09
        • 1970-01-01
        相关资源
        最近更新 更多