繁体   English   中英

Html.DropDownList混乱

[英]Html.DropDownListFor confusion

有人可以帮我了解Html.DropDownListFor的工作原理吗? 我有一个如下模型

public class TestModel
{
    public IList<SelectListItem> ProductNames { get; set; }
    public string Product { get; set; }
}

调用DropDownListFor看起来像

@Html.DropDownListFor(model => model.ProductNames,  Model.ProductNames, "Select a Product", new {@class="selectproductname" })

通过此设置,我发现下拉列表已正确填充,但是提交表单后,我似乎无法获取所选项目。 同样从我阅读的内容来看,对Html.DropDownListFor的调用实际上应该像

@Html.DropDownListFor(model => model.Product,  Model.ProductNames, "Select a Product", new {@class="selectproductname" })

实际上,代码的其他部分也是如此,但是当我这样做时,下拉列表并未被填充。 我在这里想念什么吗?

一些注意事项:1)此下拉列表的填充发生在从另一个下拉列表中选择一个值之后,因此我通过调用getJSON从数据库中获取数据来进行AJAX调用2)该应用程序是MVC应用程序

将不胜感激提供的任何帮助。 让我知道您是否需要其他信息来帮助回答这个问题

编辑:这是更多详细信息

这是控制器中用于检索下拉菜单数据的操作方法

[AcceptVerbs(HttpVerbs.Get)]
    public JsonResult LoadProductsBySupplier(string parentId)
    {
        var ctgy = this._categoryService.GetAllCategoriesByParentCategoryId(Convert.ToInt32(parentId));
        List<int> ctgyIds = new List<int>();

        foreach (Category c in ctgy)
        {
            ctgyIds.Add(c.Id);
        }

        var prods = this._productService.SearchProducts(categoryIds: ctgyIds, storeId: _storeContext.CurrentStore.Id, orderBy: ProductSortingEnum.NameAsc);

        products = prods.Select(m => new SelectListItem()
        {
            Value = m.Id.ToString(),
            Text = m.Name.Substring(m.Name.IndexOf(' ') + 1)
        });

        var p = products.ToList();
        p.Insert(0, new SelectListItem() { Value = "0", Text = "Select A Product" });
        products = p.AsEnumerable();
        //model.ProductNames = products.ToList();


        return Json(products, JsonRequestBehavior.AllowGet);
    }

这是对控制器中动作的JQuery调用

$("#Supplier").change(function () {
        var pID = $(this).val();            
        $.getJSON("CoaLookup/LoadProductsBySupplier", { parentId: pID },
                function (data) {
                    var select = $("#ProductNames");
                    select.empty();
                    if (pID != "0") {
                        $.each(data, function (index, itemData) {
                            select.append($('<option/>', {
                                value: itemData.Value,
                                text: itemData.Text
                            }));
                        });
                    }
                });
    });

当我使用model => model.Product时,即使在变量data中返回了数据,也不会进入$ .each循环

第二种用法是正确的,但是当您使用

@Html.DropDownListFor(model => model.Product, .....

您正在生成具有属性id="Product"<select> ,因此您需要更改脚本以引用具有此ID的元素

....
$.getJSON("CoaLookup/LoadProductsBySupplier", { parentId: pID }, function (data) {
  var select = $("#Product"); // change this selector
  select.empty();
  ....

编辑

顺便说一句,您不一定需要在控制器方法中创建SelectList ,并且您的代码可以简化为

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult LoadProductsBySupplier(int parentId)
{
  List<int> ctgyIds = _categoryService.GetAllCategoriesByParentCategoryId(parentId).Select(c => c.ID).ToList();
  var products= _productService.SearchProducts(categoryIds: ctgyIds, storeId: _storeContext.CurrentStore.Id, orderBy: ProductSortingEnum.NameAsc).AsEnumerable().Select(p => new
  {
    ID = p.ID,
    Text = p.Name.Substring(m.Name.IndexOf(' ') + 1)
  });
  return Json(products, JsonRequestBehavior.AllowGet);
}

和脚本

$("#Supplier").change(function () {
  var pID = $(this).val();
  var select = $("#Product").empty().append($('<option/>').text('Select A Product'));
  if (pID == '0') { return; } // this should really be testing for null or undefined but thats an issue with your first select          
  $.getJSON('@Url.Action("LoadProductsBySupplier", "CoaLookup")', { parentId: $(this).val() }, function (data) {
    $.each(data, function (index, item) {
      select.append($('<option/>').val(item.ID).text(item.Text);
    });
  });
});

还要注意在脚本中$.getJSON之前的if子句-调用服务器然后决定忽略返回值没有多大意义

要在“编辑”页面中获取选定的值,请尝试使用:

@Html.DropDownList("name", new SelectList(ViewBag.Product, "Id","Name", item.Id))

在这个项目中,item.Id是选定的值,而ViewBag.Product必须使用linq从产品中填充,例如在Controller中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM