C# Html.dropdownlist以防混淆

C# Html.dropdownlist以防混淆,c#,asp.net-mvc,html.dropdownlistfor,C#,Asp.net Mvc,Html.dropdownlistfor,有人能帮我理解Html.DropDownListFor是如何工作的吗? 我有一个模型如下 public class TestModel { public IList<SelectListItem> ProductNames { get; set; } public string Product { get; set; } } 通过这种设置,我发现下拉列表填充正确,但是在提交表单后,我似乎无法获得所选项目。从我读到的内容来看,调用Html.DropDownListFo

有人能帮我理解Html.DropDownListFor是如何工作的吗? 我有一个模型如下

public class TestModel
{
    public IList<SelectListItem> ProductNames { get; set; }
    public string Product { get; set; }
}
通过这种设置,我发现下拉列表填充正确,但是在提交表单后,我似乎无法获得所选项目。从我读到的内容来看,调用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时未进入的每个循环,即使变量数据中返回了数据

要在编辑页面中获取所选值,请尝试使用:

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

在本例中,item.Id是所选的值,而ViewBag.Product必须使用linq从产品中填充,例如在控制器中

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

@Html.DropDownListFor(model => model.Product, .....
您正在生成一个属性为id=Product的元素,因此需要更改脚本以引用具有此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子句-调用服务器然后决定忽略返回值没有多大意义

第二种用法是正确的。属性的值将是所选选项的值,但您尚未显示如何在ajax调用中填充选项,因此很难知道问题出在何处。向我们显示如何填充IList ProductNames这一切取决于SelectListItem的值部分。正如@StephenMuecke所说,如果您在使用model=>model时将产品值分配给ProductNames ListItem的值部分,则第二种用法是正确的。ajax成功回调中的产品使用如下var select=$Product或var select=$。selectproductname选择器可以是id或.className感谢Venkata。我知道这一定是件傻事。我非常感谢你的帮助,非常感谢Stephen,我也非常感谢你给我一些关于如何改进代码的建议。我总是试图寻求这样的建议
$("#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);
    });
  });
});