【问题标题】:Dynamic DropDownLists In MVC 4 FormMVC 4 形式的动态下拉列表
【发布时间】:2016-06-08 04:49:01
【问题描述】:

我的最终目标是能够在一个 DropDownList 中选择一个值,并且在做出该选择之后,我希望根据在第一个中所做的选择来填充另一个 DropDownList。我的表单应该有一个包含省份列表的 DropDownList 和一个包含所选省份城市的 DropDownList。

我是 ASP MVC 的新手,所以我不确定这将如何完成。如果这必须在 Winforms 或 WPF 中完成,我将能够实现它,因为我知道数据如何从我的业务逻辑传播到显示给用户的控件 - 但是在 MVC 中,我不知道如何做到这一点正确有效。我也在学习 javascript 和相关帮助程序(例如 jQuery),所以我需要一些帮助来使用 ajax 之类的东西来实现我的目标。

这是我已经拥有的以及我知道实现目标应该拥有的:

我的模型(捕获用户的输入):

    public class CaptureCreateTrip
    {
        [Required]
        [Display(Name = "Trip ID")]
        public string TripID { get; set; }

        [Required]
        public string StartPointProvince { get; set; }

        [Required]
        public string StartPointCity { get; set; }

        [Required]
        public string EndPointProvince { get; set; }

        [Required]
        public string EndPointCity { get; set; }
    }

我的表格:

请记住,我只是插入 ViewBag 引用以充当占位符,直到我可以用动态数据替换它。

@using (Html.BeginForm("CreateOneWayTrip", "Trips"))
        {
            @Html.ValidationSummary(false);
            <fieldset>
                <legend>Enter Your Trip Details</legend>

                <label>Start Point</label>
                @Html.DropDownListFor(m => m.StartPointProvince, (SelectList)ViewBag.Provinces);
                @Html.DropDownListFor(m => m.StartPointCity, (SelectList)ViewBag.Cities);

                <label>End Point</label>
                @Html.DropDownListFor(m => m.EndPointProvince, (SelectList)ViewBag.Provinces);
                @Html.DropDownListFor(m => m.EndPointCity, (SelectList)ViewBag.Cities);

                <p style="float: none; text-align: center;">
                    <button type="submit" value="Create" class="btn btn-info btn-circle btn-lg">
                        <i class="fa fa-check"></i>
                    </button>

                    <button type="submit" value="Create" class="btn btn-warning btn-circle btn-lg">
                        <i class="fa fa-times"></i>
                    </button>
                </p>
            </fieldset>
        }

控制器:

        //To Show Create Page
        public ActionResult Create()
        {
            return View();
        }

        // To Get Data after post
        [HttpPost]
        public ActionResult Create(Models.CaptureCreateTrip trip)
        {
            Models.CaptureCreateTrip t = trip;

            return Redirect("~/Trips/Index");
        }

        //Will I need a controller to get json data?

另外,我必须在我的页面中包含什么 javascript 以 (1) 在下拉列表中触发选择更改事件和 (2) 获取适当的数据(所选省份的城市列表)。

更新:

这是生成的页面源的sn-p:

<select Id="province_dll" class="form-control" data-val="true" data-val-required="The StartPointProvince field is required." id="StartPointProvince" name="StartPointProvince"><option value="NC">Northern Cape</option>
<option value="FS">Free State</option>
<option value="WC">Western Cape</option>
</select>
                <select Id="city_dll" class="form-control" data-val="true" data-val-required="The StartPointCity field is required." id="StartPointCity" name="StartPointCity"><option value="NC">Kimberley</option>
<option value="FS">Boshof</option>
<option value="WC">Barkley</option>
</select>

这是我写的 javascript:

$("province_dll").change(function () {
        $.ajax({
            url: 'getCities/Trips',
            type: 'post',
            data: {
                provinceId: $("province_dll").val()
            }
        }).done(function (response) {
            $("cities_dll").html(response);
        });
    });

这是我的控制器(ps。数据只是测试数据,稍后将连接到db):

    [HttpPost]
    public ActionResult getCicites(int provinceId)
    {
        var lstCities = new SelectList(new[] { "City1", "City2", "City3" });

        return Content(String.Join("", lstCities));
    }

但它仍然无法正常工作 - 当我在第一个 DropDownList 中选择不同的值时,没有任何反应。

【问题讨论】:

    标签: javascript c# ajax asp.net-mvc


    【解决方案1】:

    你应该在省 ddl 的 change 事件中创建一个 ajax 调用。 此调用将请求执行操作并返回所选省份的城市。

    $("province_dll").change(function(){
        $.ajax({
             url: 'getCitiesController/getCitiesAction',
             type: 'post',
             data: {
                   provinceId: provinceIdVar
             }
        }).done(function(response){
             $("cities_dll").html(response);
        }); 
    });
    

    在行动中:

    [HttpPost]
    public ActionResult getCicitesAction(int provinceId)
    {
         var cities = db.cities.Where(a => a.provinceId == provinceId).Select(a => "<option value='" + a.cityId + "'>" + a.cityName + "'</option>'";
    
         return Content(String.Join("", cities));
    }
    

    【讨论】:

    • 只是一个简单的问题 - 'provinceIdVar' 变量是什么,我从哪里得到它?
    • @MarnusSteyn ProvinceIdVar 是省下拉列表的值。你可以像这样得到它:$("province_dll").val();
    • 我更新了我的帖子,如果你可以看看。只需查看“更新”文本之后的内容。
    • 我在 ajax 代码的 .done 中插入了一个 'alert("response)' 以确认正在获取数据并查看返回的内容,当我在 DropDownList 中选择一个项目时事件触发是因为确实弹出了警报,但“响应”字段中返回的值等于“System.Web.Mvc.SelectListItemSystem.Web.Mvc.SelectListItemSystem.Web.Mvc.Select‌​ListItem”
    【解决方案2】:

    所以我假设第一个下拉列表按原样在 ViewBag 中传递,但您需要根据第一个列表中选择的任何项目来填充第二个下拉列表。对吗?

    基本上,这相当于从 dropbox1 选择的视图中进行 AJAX 调用,从控制器中的 JsonResult 操作中获取返回的数据,并从中构建第二个下拉列表。

    稍加联系,您可能会发现the following post 提供了您需要的大部分内容。

    来自那个帖子:

    查看:

    <script type="text/javascript">
    $('body').on('change', '.combo', function () {
       var selectedValue = $(this).val();
       alert(selectedValue);
       $.get("/Home/getcity", { country: selectedValue }, function (data) {
           $("#tese").html(data);
           $(".combo2").html("<option value = \"\"></option>")
           $.each(data, function (index, value) {
              $(".combo2").append("<option value = \"" + value + "\">" + value + "</option>");
           });
           $(".combo2").html()
       });
    });
    </script>
    

    和控制器:

    public JsonResult getCity(string country)
    {
        var temp = (from cntry in db.Table3.OrderBy(s => s.country)
                    where (string.Compare(cntry.country, country) == 0)
                    select cntry.city).ToList();
        return Json(temp, JsonRequestBehavior.AllowGet);
    }
    

    当然,示例有所不同,但一般方法是相同的:找到选定的值并发出 AJAX 请求;使用 Linq,为第二个选择列表获取必要的数据;将结果以 Json 对象的形式返回给视图。

    【讨论】:

      猜你喜欢
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多