使用剃刀而不是 HTML 的下拉列表<select>



我有一个类似的选择列表

  <select id="select-product">
            <option>Select a Product</option>
  </select>

我在运行时使用Ajax填写这个列表,现在我想将其转换为剃刀视图,在重定向到页面之前,我将在Viewbag中包含数据。

我该怎么做?

在重定向到页面之前,我将在Viewbag中包含数据。

一个常见的(也是好的)方法是在您的视图中使用@Html.DropDownList()@Html.DropDownListFor<>()。但是,您应该更喜欢ViewBag中的强类型模型,而不是结构化程度较低的数据。

另请参阅:

  • 如何编写一个简单的Html.DropDownListFor()
  • 何时在Mvc3中使用ViewBag、ViewData或TempData
$(document).ready(function () {
    $.get('/Home/GetProducts/' + $(this).val(), function (response) {
        var products = $.evalJSON(response);
        var ddlSelectedProduct = $("#SelectedProduct");
        // clear all previous options 
        $("#SelectedProduct > option").remove();
        // populate the products 
        for (i = 0; i < products.length; i++) {
            ddlSelectedProduct.append($("<option />").val(products[i].Value).text(products[i].Text));
        }
    });
});

@Html.DropDownListFor(
    x => x.SelectedProductId, 
    new SelectList(ViewBag.Products as SelectList, "Value", "Text"),
    "-- Select Product--"
)

最新更新