Html.DropDownListFor混乱 [英] Html.DropDownListFor confusion

查看:113
本文介绍了Html.DropDownListFor混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我了解Html.DropDownListFor是如何工作的?
我有一个模型,该模型如下:

Can someone please help me understand how the Html.DropDownListFor works? I have a model which is as follows

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

要DropDownListFor调用它看起来像

The call to DropDownListFor which looks like

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

有了这个设置我发现下拉列表中得到正确但在提交表单后,我似乎无法获得所选择的项目填充。另外从我读过调用Html.DropDownListFor实际上应该看起来像

With this set up I find that the drop down list gets populated correctly however after submitting the form I can't seem to get the selected item. Also from what I've read the call to Html.DropDownListFor should actually look like

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

在事实上以及在code看起来像其他地区的,但是当我做这个下拉列表不被填充。我失去了一些东西在这里?

In fact other parts of the code look like that as well but when I do this the drop down list is not being populated. Am I missing something here?

一对夫妇的旁注:
1)这种下降的人口出现下降从另一个下拉这么一个价值选择之后,我调用的getJSON从数据库中获取数据,从AJAX请求
2)应用程序是一个MVC应用程序

A couple of side notes: 1) The population of this drop down occurs after selection of a value from another drop down so I make an AJAX call by calling getJSON to get data from the database 2) The application is an MVC application

请问AP preciate提供任何帮助。让我知道如果你需要任何其他信息,以帮助回答这个问题。

Would appreciate any help offered. Let me know if you need any other information to help answer this question

编辑:
这里有一些更多的细节。

Here are some more details

这是在控制器中的操作方法用于检索的降下来的数据

This is the action method in the controller used to retrieve the data for the drop down

[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的调用动作控制器

And this is the JQuery call to the action in the controller

$("#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.Product即使数据在可变数据返回

It's this $.each loop that doesn't get entered into when I use model => model.Product even though data is returned in the variable data

推荐答案

第二个用法是正确的,但是当你使用

The second usage is correct, however when you use

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

要生成一个&LT;选择&GT; 的属性 ID =产品,所以你需要改变你的脚本参考元素与此ID

you are generating a <select> with the attribute id="Product" so you need to change your script to refer to the element with this ID

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

修改

作为一个方面不行,你不一定需要建立一个在你的控制器方法,你code可以简化为的SelectList

As a side not, you do not necessarily need to create a SelectList in your controller method and you code could be simplified to

[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 如果子句 - 没有太多的点调用服务器然后决定忽略返回值

Note also in the script the if clause before $.getJSON - there is not much point calling the server then deciding to ignore the return value

这篇关于Html.DropDownListFor混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆