填充孩子下拉依据是什么,从父下拉列表中选择 [英] Populating child drop down based on what was selected from parent drop down list

查看:114
本文介绍了填充孩子下拉依据是什么,从父下拉列表中选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery和ASP.NET MVC 3的最新版本的剃刀视图引擎。

我曾尝试谷歌寻找装载一个孩子下拉列表中,当父下拉项选择一个体面的例子。我期待通过的jQuery AJAX 用做 JSON 。我这方面的知识是零。

我有一个类别列表中的类别类。这是父子关系。

如果我选择从父类别下拉列表中,那么所有的子类别需要被列在子下拉列表中选择父类别。

这是我现在有,但需要去完成它,不知道如果我在正确的方向:

  $(文件)。就绪(函数(){
   $('#ddlParentCategories')。改变(函数(){
      警报('改变');
   });
});
 

我装我的下拉列表,从我的视图模型为这样:

  @ Html.DropDownListFor(X => x.ParentCategoryId,新的SelectList(Model.ParentCategories,ID,名称,Model.ParentCategoryId), - 选择 -  - ,新{ID =ddlParentCategories})
 

第一项有文字 - 选择 - (为父母和孩子下拉列表)。在初始页面加载任何必须在孩子被加载下拉列表。当选择了一个值,那么孩子下拉列表必须填充。而当 - 选择 - 再次选择在父下拉列表,然后所有项目在孩子下拉列表中必须清除,除非 - 选择 - 。

如果可能的话,如果孩子类别加载,我怎么显示圆加载图标?

更新

我已经更新了我的code到达林的code,我不能让它正常工作:

类别类:

 公共类目录
{
   公众诠释编号{获得;组; }
   公共字符串名称{;组; }
   公共字符串描述{获得;组; }
   公共字符串的MetaKeywords {获得;组; }
   公共字符串MetaDescription {获得;组; }
   公共布尔IsActive {获得;组; }
   公众诠释? ParentCategoryId {获得;组; }
   公共虚拟目录ParentCategory {获得;组; }
   公共虚拟的ICollection<类别> ChildCategories {获得;组; }
}
 

EditProductViewModel 类:

 公共类EditProductViewModel
{
   公众诠释编号{获得;组; }
   公共字符串名称{;组; }
   公共字符串ShortDescription {获得;组; }
   公共字符串LongDescription {获得;组; }
   公共布尔IsActive {获得;组; }
   公共字符串的PageTitle {获得;组; }
   公共BOOL OverridePageTitle {获得;组; }
   公共字符串的MetaKeywords {获得;组; }
   公共字符串MetaDescription {获得;组; }
   公众诠释ParentCategoryId {获得;组; }
   公开的IEnumerable<类别> ParentCategories {获得;组; }
   公众诠释ChildCategoryId {获得;组; }
   公开的IEnumerable<类别> ChildCategories {获得;组; }
}
 

ProductController的类:

 公众的ActionResult创建()
{
   EditProductViewModel视图模型=新EditProductViewModel
   {
      ParentCategories = categoryService.GetParentCategories()
         。凡(X => x.IsActive)
         .OrderBy(X => x.Name)
      ChildCategories = Enumerable.Empty<类别>()
      IsActive =真
   };

   返回视图(视图模型);
}

公众的ActionResult AjaxBindingChildCategories(INT parentCategoryId)
{
   IEnumerable的<类别> childCategoryList = categoryService.GetChildCategoriesByParentCategoryId(parentCategoryId);

   返回JSON(childCategoryList,JsonRequestBehavior.AllowGet);
}
 

创建查看:

 < TR>
   < TD><标签>相关类别:< /标签> <跨度类=红> *< / SPAN>< / TD>
   < TD> @ Html.DropDownListFor(X => x.ParentCategoryId,
         新的SelectList(Model.ParentCategories,ID,名称,Model.ParentCategoryId)
          -  选择  - ,
         新{data_url = Url.Action(AjaxBindingChildCategories),ID =ParentCategories}
      )
      @ Html.ValidationMessageFor(X => x.ParentCategoryId)
   < / TD>
< / TR>
&其中; TR>
   < TD><标签>儿童分类:其中; /标签> <跨度类=红> *< / SPAN>< / TD>
   < TD> @ Html.DropDownListFor(X => x.ChildCategoryId,
         新的SelectList(Model.ChildCategories,ID,名称,Model.ChildCategoryId)
          -  选择  - ,
         新的id {=ChildCategories}
      )
      @ Html.ValidationMessageFor(X => x.ChildCategoryId)
   < / TD>
< / TR>

<脚本类型=文/ JavaScript的>

   $(文件)。就绪(函数(){
      $('#ParentCategories')。改变(函数(){
         VAR URL = $(本)的.d​​ata(URL);
         VAR数据= {parentCategoryId:$(本).VAL()};

         $ .getJSON(URL,数据功能(childCategories){
            VAR childCategoriesDdl = $('#ChildCategories');
            childCategoriesDdl.empty();

            $每个(childCategories,函数(指数,childCategory){
               childCategoriesDdl.append($('<选项/>',{
                  值:childCategory,文本:childCategory
               }));
            });
         });
      });
   });


< / SCRIPT>
 

它进入我的AjaxBindingChildCategories行动,并将其带回记录,它只是不希望显示我的孩子类别的DropDownList。我在火错误一看,错误,我得到的是:

  GET AjaxBindingChildCategories?parentCategoryId = 1

500内部服务器错误
 

解决方案

下面是级联的一个例子下拉列表。与往常一样先定义一个视图模型:

 公共类MyViewModel
{
    [DisplayName的(国家)]
    [需要]
    公共字符串国家code {获得;组; }
    公开的IEnumerable< SelectListItem>国家{获得;组; }

    公共字符串市{获得;组; }
    公开的IEnumerable< SelectListItem>城市{获得;组; }
}
 

然后控制器:

 公共类的HomeController:控制器
{
    公众的ActionResult指数()
    {
        VAR模型=新MyViewModel
        {
            // TODO:从什么地方获取的国家
            国家=新的[]
            {
                新SelectListItem {值=FR,文本=法国},
                新SelectListItem {值=美,文本=USA},
            },

            //首先我们设定的城市DDL空
            城市= Enumerable.Empty< SelectListItem>()
        };
        返回查看(模型);
    }

    公众的ActionResult城市(字符串国code)
    {
        // TODO:根据所选择的国家返回的城市:
        VAR城市=新的[]
        {
            巴黎,马赛,里昂
        };
        返回JSON(市,JsonRequestBehavior.AllowGet);
    }
}
 

一个观点:

  @model MyViewModel

@using(Html.BeginForm())
{
    < D​​IV>
        @ Html.LabelFor(X => x.Country code)
        @ Html.DropDownListFor(
            X => x.Country code,
            Model.Countries,
             -  选择国家  - ,
            新{data_url = Url.Action(城市)}
        )
        @ Html.ValidationMessageFor(X => x.Country code)
    < / DIV>

    < D​​IV>
        @ Html.LabelFor(X => x.City)
        @ Html.DropDownListFor(
            X => x.City,
            Model.Cities,
             - 选择城市 - 
        )
        @ Html.ValidationMessageFor(X => x.City)
    < / DIV>

    < P><输入类型=提交值=OK/>< / P>
}
 

终于在一个单独的文件中不显眼的JavaScript:

  $(函数(){
    $('#国家code')。改变(函数(){
        VAR URL = $(本)的.d​​ata(URL);
        VAR数据= {国家code:$(本).VAL()};
        $ .getJSON(URL,数据功能(市){
            VAR citiesDdl = $('#城市');
            citiesDdl.empty();
            $每个(市,函数(指数,市){
                citiesDdl.append($('<选项/>',{
                    价值:城市,
                    文字:城市
                }));
            });
        });
    });
});
 

I am using the latest version of jQuery and ASP.NET MVC 3 with the Razor view engine.

I have tried Google looking for a decent example of loading a child drop down list when a parent drop down item is selected. I am looking to do this via jQuery AJAX using JSON. My knowledge of this is zero.

I have a Category class with a list of categories. It's a parent-child association.

If I select a category from the parent drop down list, then all the child categories need to be listed in the child drop down list for the selected parent category.

This is what I currently have, but need to complete it, not sure if I am in the right direction:

$(document).ready(function () {
   $('#ddlParentCategories').change(function () {
      alert('changed');
   });
});

I loaded my drop down list from my view model as such:

@Html.DropDownListFor(x => x.ParentCategoryId, new SelectList(Model.ParentCategories, "Id", "Name", Model.ParentCategoryId), "-- Select --", new { id = "ddlParentCategories" })

The first item has text "-- Select --" (for both parent and child drop down lists). On initial page load nothing must be loaded in the child drop down list. When a value is selected then the child drop down list must be populated. And when "-- Select --" is selected again in the parent drop down list then all the items in the child drop down list must cleared except "-- Select --".

If possible, if the child categories is loading, how do I display that "round" loading icon?

UPDATE

I have updated my code to Darin's code, and I cannot get it to work properly:

Category class:

public class Category
{
   public int Id { get; set; }
   public string Name { get; set; }
   public string Description { get; set; }
   public string MetaKeywords { get; set; }
   public string MetaDescription { get; set; }
   public bool IsActive { get; set; }
   public int? ParentCategoryId { get; set; }
   public virtual Category ParentCategory { get; set; }
   public virtual ICollection<Category> ChildCategories { get; set; }
}

EditProductViewModel class:

public class EditProductViewModel
{
   public int Id { get; set; }
   public string Name { get; set; }
   public string ShortDescription { get; set; }
   public string LongDescription { get; set; }
   public bool IsActive { get; set; }
   public string PageTitle { get; set; }
   public bool OverridePageTitle { get; set; }
   public string MetaKeywords { get; set; }
   public string MetaDescription { get; set; }
   public int ParentCategoryId { get; set; }
   public IEnumerable<Category> ParentCategories { get; set; }
   public int ChildCategoryId { get; set; }
   public IEnumerable<Category> ChildCategories { get; set; }
}

ProductController class:

public ActionResult Create()
{
   EditProductViewModel viewModel = new EditProductViewModel
   {
      ParentCategories = categoryService.GetParentCategories()
         .Where(x => x.IsActive)
         .OrderBy(x => x.Name),
      ChildCategories = Enumerable.Empty<Category>(),
      IsActive = true
   };

   return View(viewModel);
}

public ActionResult AjaxBindingChildCategories(int parentCategoryId)
{
   IEnumerable<Category> childCategoryList = categoryService.GetChildCategoriesByParentCategoryId(parentCategoryId);

   return Json(childCategoryList, JsonRequestBehavior.AllowGet);
}

Create view:

<tr>
   <td><label>Parent Category:</label> <span class="red">*</span></td>
   <td>@Html.DropDownListFor(x => x.ParentCategoryId,
         new SelectList(Model.ParentCategories, "Id", "Name", Model.ParentCategoryId),
         "-- Select --",
         new { data_url = Url.Action("AjaxBindingChildCategories"), id = "ParentCategories" }
      )
      @Html.ValidationMessageFor(x => x.ParentCategoryId)
   </td>
</tr>
<tr>
   <td><label>Child Category:</label> <span class="red">*</span></td>
   <td>@Html.DropDownListFor(x => x.ChildCategoryId,
         new SelectList(Model.ChildCategories, "Id", "Name", Model.ChildCategoryId),
         "-- Select --",
         new { id = "ChildCategories" }
      )
      @Html.ValidationMessageFor(x => x.ChildCategoryId)
   </td>
</tr>

<script type="text/javascript">

   $(document).ready(function () {
      $('#ParentCategories').change(function () {
         var url = $(this).data('url');
         var data = { parentCategoryId: $(this).val() };

         $.getJSON(url, data, function (childCategories) {
            var childCategoriesDdl = $('#ChildCategories');
            childCategoriesDdl.empty();

            $.each(childCategories, function (index, childCategory) {
               childCategoriesDdl.append($('<option/>', {
                  value: childCategory, text: childCategory
               }));
            });
         });
      });
   });


</script>

It goes into my AjaxBindingChildCategories action and it brings back records, it just doesn't want to display my child category dropdownlist. I had a look in Fire Bug and the error that I get is:

GET AjaxBindingChildCategories?parentCategoryId=1

500 Internal Server Error

解决方案

Here's an example of cascading drop down lists. As always start by defining a view model:

public class MyViewModel
{
    [DisplayName("Country")]
    [Required]
    public string CountryCode { get; set; }
    public IEnumerable<SelectListItem> Countries { get; set; }

    public string City { get; set; }
    public IEnumerable<SelectListItem> Cities { get; set; }
}

then a controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            // TODO: Fetch countries from somewhere
            Countries = new[]
            {
                new SelectListItem { Value = "FR", Text = "France" },
                new SelectListItem { Value = "US", Text = "USA" },
            },

            // initially we set the cities ddl to empty
            Cities = Enumerable.Empty<SelectListItem>()
        };
        return View(model);
    }

    public ActionResult Cities(string countryCode)
    {
        // TODO: based on the selected country return the cities:
        var cities = new[]
        {
            "Paris", "Marseille", "Lyon"
        };
        return Json(cities, JsonRequestBehavior.AllowGet);
    }
}

a view:

@model MyViewModel

@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.CountryCode)
        @Html.DropDownListFor(
            x => x.CountryCode, 
            Model.Countries, 
            "-- Select country --", 
            new { data_url = Url.Action("cities") }
        )
        @Html.ValidationMessageFor(x => x.CountryCode)
    </div>

    <div>
        @Html.LabelFor(x => x.City)
        @Html.DropDownListFor(
            x => x.City, 
            Model.Cities, 
            "-- Select city --"
        )
        @Html.ValidationMessageFor(x => x.City)
    </div>

    <p><input type="submit" value="OK" /></p>
}

and finally the unobtrusive javascript in a separate file:

$(function () {
    $('#CountryCode').change(function () {
        var url = $(this).data('url'); 
        var data = { countryCode: $(this).val() };
        $.getJSON(url, data, function (cities) {
            var citiesDdl = $('#City');
            citiesDdl.empty();
            $.each(cities, function (index, city) {
                citiesDdl.append($('<option/>', {
                    value: city,
                    text: city
                }));
            });
        });
    });
});

这篇关于填充孩子下拉依据是什么,从父下拉列表中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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