1

我继承了一个完成了一半的 MVC 项目,该项目是为了跟踪我们客户产品的许可证。

许可证 Create.cshtml 页面上有两个下拉列表,第一个允许您选择客户,第二个然后填充客户拥有的产品 (CustomerProducts) 以允许您选择要创建的 CustomerProduct许可,如下:

<div class="editor-label">Customer</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.SelectedCustomerId, new SelectList(Model.Customers, "Id", "Name"), "-- Select Customer --")
    @Html.ValidationMessageFor(model => model.SelectedCustomerId)
</div>

<div class="editor-label">Product</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.SelectedCustomerProductId, Enumerable.Empty<SelectListItem>(), "-- Select Product --")
    @Html.ValidationMessageFor(model => model.SelectedCustomerProductId)
</div>

我遇到的问题是 CustomerProducts 与产品版本相关联,但下拉列表仅显示产品名称,而不是版本名称,因此如果客户同时拥有“产品名称 v1.0”和“产品名称 v1.0”。 1" 下拉列表仅显示 Productname 两次。所以我要寻找的是(伪代码):

@Html.DropDownListFor(model => model.SelectedCustomerProductId + " (" + model.SelectedCustomerProductId.ProductVersion.Name + ")", Enumerable.Empty<SelectListItem>(), "-- Select Product --")

我确信必须有一种简单的方法来让该下拉列表同时显示产品和版本,但我已经搜索并搜索了我能想到的所有来源,但无法提出解决方案。

抱歉,如果这是一个基本问题;我是 MVC 的新手,花了几天时间寻找解决方案,以解决在我看来应该是一个非常简单的问题!

编辑:

遵循@von v. 的以下建议,向 CustomerProduct 添加了一个只读属性:

public virtual string ProductVersionFullName { get { return Product.Name + " (" + ProductVersion.Name + ")"; } }

这只是使用该属性作为显示成员的情况,而不是尝试绑定到下拉列表中 CustomerProduct 的多个属性(下拉列表由设置显示成员的 LicensesController 中的方法填充)。我知道我错过了一些简单的东西!

4

1 回答 1

2

的第一个参数DropDownListFor定义为

标识包含要显示的属性的对象的表达式

如果您正在调查,那可能会让您感到困惑。但基本上第一个参数是“指向”模型属性的表达式,您希望下拉列表的值绑定到该属性。在您的情况下,您的模型有一个属性SelectedCustomerProductId,这就是下拉列表的选定值将被“放入”的地方。那应该是一个单一的属性。如果要在下拉列表中显示更多文本,则需要将其构建到 selectlistitem 中。

因此,在您的控制器方法中,您将拥有以下内容:

// this is where you build your model
var model =initializeYourModel();

// this is where you build the Products
// whose values are used in the DropDownList.
// I assume you already have the code that builds the list,
// this is just an example that shows 
// where you should build the "Product and the Version"
model.Products = new List<SelectListItem>
{
    new SelectListItem{ Value = "1", Text = "the name " + "the version"},
};
于 2013-04-10T11:08:25.813 回答