【问题标题】:Binding The Collection of data in drop down list in mvc4在 mvc4 的下拉列表中绑定数据集合
【发布时间】:2013-11-19 07:17:03
【问题描述】:

在我看来,我的代码如下所示。

@if (!Model.DisableBuyButton || !Model.DisableWishlistButton)
{

    <div class="qutblk">

    <span>@Html.LabelFor(model => model.EnteredQuantity, new { @class = "input-small" }, " :")</span>
        @if (Model.AllowedQuantities.Count > 0)
        {
            @Html.DropDownListFor(model => model.EnteredQuantity, Model.AllowedQuantities, new { @class = "input-small" })
        }
        else
        {
            @Html.TextBoxFor(model => model.EnteredQuantity, new { @class = "input-small" })
        }




} @Html.Widget("productdetails_add_info")
</div>

如果我有 ALLOWEDQUANTITIES.COUNT 更多然后 0.I 需要下拉列表的数量。

例如,如果数量是 5,我需要在下拉列表中添加 1,2,3,4,5 数字。如果数量是 7,我需要在下拉列表中添加 1,2,3,4,5,6,7 数字。

但我的问题是我无法在下拉列表中绑定数字等数据,这意味着如果数量为 5,它只会在下拉列表中显示 5 个数字而不显示 1,2,3,4,5

【问题讨论】:

  • 如果你给它 5 作为数量,你的视图没有任何逻辑来生成像1,2,3,4,5 这样的数字。你怎么能指望剃须刀做到这一点?你为什么不写一个自定义助手来做你所期望的?

标签: asp.net-mvc-4 razor


【解决方案1】:

你可以试试这样的:

public static class MyLists
    {
    public static List<SelectListItem> GetList()
    {
    List<SelectListItem> result = new List<SelectListItem>(int AllowedQuantities)

    for(int i = 0; i < AllowedQuantities; i++)
    {
     var number = i + 1;
     var item = new SelectListItem {text = number.ToString(), value = number.ToString()};
     result.Add(item);
    }

    return result
    }
    }

在你看来:

@Html.DropDownListFor(model => model.EnteredQuantity, MyLists.GetList(model.EnteredQuantity), new { @class = "input-small" })

【讨论】:

  • 我写的如下
  • @Html.DropDownListFor(model => model.EnteredQuantity, Model.GetList(model.EnteredQuantity) ,new { @class= "input-small" }) 其显示错误如“模型名称不存在当前上下文。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-26
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-26
相关资源
最近更新 更多