0

在我的视图文件中,我当前具有以下代码:

    @if ((Model.CustomerOrderTrackings != null) && (Model.CustomerOrderTrackings.Count > 0)) {
        for (int i = 0; i < Model.CustomerOrderTrackings.Count; i++) {
            @Html.EditorFor(m => m.CustomerOrderTrackings[i])
        }
    } else {
        @*The problem is here*@
        @Html.EditorFor(m => new CustomerOrderTracking())
    }

然后,我的编辑器模板如下所示:

@model Models.CustomerOrderTracking

<tr class="gridrow">
    <td class="carrierName">
        @Html.HiddenFor(m => m.Id, new { id = "" })
        @Html.HiddenFor(m => m.ShipperId, new { id = "", @class = "trackingShipperId" })
        @Html.DropDownListFor(m => m.CarrierName, ViewExtensions.ToFriendlySelectList<CustomerOrderTracking.CarrierNames>(Model.CarrierName), new { id = "" })
    </td>
    <td class="service">@Html.DropDownListFor(m => m.ShippingType, ViewExtensions.ToFriendlySelectList<CustomerOrderTracking.ShippingTypes>(Model.ShippingType), new { id = "" })</td>
    <td class="trackingNumber">@Html.TextBoxFor(m => m.ShippingTrackingNumber, new { @class = "trackingInput", id = "" }) <a href="" target="_blank" class="icon track"></a></td>
    <td class="shippingCost">
        @Html.TextBoxFor(m => m.ShippingCost, new { @class = "shippingInput", id = "" })
        <div onclick="Operations.Orders.DeleteTrackingRow(this)" class="icon delete deleteTracking" title="Delete this shipment?"></div>
    </td>
</tr>

我要做的是在当前没有任何项目附加到对象的情况下向该表添加默认行。对象的新实例不起作用,因为这会导致以下错误:Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

我可以手动编码输入,但是我的代码相当草率,因为我将使用手动编码输入,然后从 ASP.NET MVC 扩展自动生成输入。

有没有办法可以将对象的默认实例传递给我的编辑器模板?

4

2 回答 2

1

我在 MVC 框架中看到它的方式是,在控制器中检测您的需求并在模型到达视图之前根据需要调整模型。另一个答案,即 99% 不是宗教财产的方式,是在你的观点中有逻辑(ew!)。

public ActionResult SomeAction()
{

  if (model.CustomerOrderTrackings == null 
      || model.CustomerOrderTrackings.Count > 0) 
  {
    // Do Something with model
  }

  this.View(model)
}
于 2012-05-14T16:00:52.410 回答
0

在我的视图文件中,我当前具有以下代码:

@if ((Model.CustomerOrderTrackings != null) && (Model.CustomerOrderTrackings.Count > 0)) {
    for (int i = 0; i < Model.CustomerOrderTrackings.Count; i++) {
        @Html.EditorFor(m => m.CustomerOrderTrackings[i])
    }
} else {
    @*The problem is here*@
    @Html.EditorFor(m => new CustomerOrderTracking())
}

解决方法是在 Html EditorFor 之外声明模型的实例。例如:

@if ((Model.CustomerOrderTrackings != null) && (Model.CustomerOrderTrackings.Count > 0)) {
    for (int i = 0; i < Model.CustomerOrderTrackings.Count; i++) {
        @Html.EditorFor(m => m.CustomerOrderTrackings[i])
    }
} else {
    @{ CustomerOrderTracking stubModel = new CustomerOrderTracking(); }
    @Html.EditorFor(m => stubModel)
}
于 2015-11-11T01:20:43.757 回答