如何在 MVC4 剃刀中实现依赖下拉列表



我需要在MVC4+Razor View中实现依赖下拉列表。我有 3 个下拉列表:国家、州和城市。所有这些都来自数据库。因此,我想从数据库中填充国家/地区列表。当我选择一个国家/地区时,在第二个下拉列表中,我应该根据该国家/地区获取关联的州。最后,在第三个下拉列表中,我应该根据所选州获取城市。我正在分享我准备的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Employee_Mgmt_System.Models
{
public class EmployeeRegistration
{
    public List<string> country = new List<string>();
    public List<string> city = new List<string>();
    public List<string> state = new List<string>();
}
}

控制器

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Employee_Mgmt_System.Models;
    using System.Data;
    using System.Data.SqlClient;
    using System.Configuration;
    namespace Employee_Mgmt_System.Controllers
    {
        public class EmployeeRegistrationController : Controller
        {
    //
    // GET: /EmployeeRegistration/
    EmployeeRegistration Er = new EmployeeRegistration();
    public ActionResult EmployeeRegistration()
    {
        Er.getCountry();
        Er.getCity();
        Er.getState();
        ViewBag.countryddl = Er.country;
        ViewBag.cityddl = Er.city;
        ViewBag.stateddl = Er.state;
        return View(Er);
    }
    [HttpPost]
    public ActionResult Register(EmployeeRegistration empRegmodel)
    {
        if (ModelState.IsValid)
        {
            Er.registerEmpInfo(empRegmodel);
            return RedirectToAction("HomeScreen", "HomeScreen");
        }
        Er.getCountry();
        Er.getCity();
        Er.getState();
        ViewBag.countryddl = Er.country;
        ViewBag.cityddl = Er.city;
        ViewBag.stateddl = Er.state;
        return View("EmployeeRegistration");
            }
        }
    }

视图

        @model Employee_Mgmt_System.Models.EmployeeRegistration
        @{
            ViewBag.Title = "EmployeeRegistration";
        }
        <body style="background-color:rgb(128,128,128)">
   
            @using (Html.BeginForm("Register", "EmployeeRegistration", FormMethod.Post))
            {
              @Html.ValidationSummary(true)
                <div style="color:red; text-align:center" >
                    <fieldset>
                        <legend>Validation Summary</legend>
                        @Html.ValidationMessageFor(m => m.Password)
                   <br />
                        @Html.ValidationMessageFor(m=>m.ConfirmPassword)
                        <br />
                        @Html.ValidationMessageFor(m=>m.EmailID)
                    </fieldset>
                </div>
               <br />
                <br />
          
                <div>
                  <table border="1" style=  "width:500px">
                           <tr>
                           <td style="width:200px">
                               @Html.LabelFor(m=>m.country)
                          </td>
                          <td>
                              @Html.DropDownListFor(m=>m.countryDDL, new SelectList(@ViewBag.CountryDDL),new {style="Width:300px"})
        @*                       @Html.DropDownListFor(m=>m.countryDDL, new SelectList(Model.country), new {style="Width:300px"})*@
                               </td>
                      </tr>
                       <tr>
                           <td style="width:200px">
                               @Html.LabelFor(m=>m.city)
                          </td>
                          <td style="width:300px">
                               @Html.DropDownListFor(m=>m.cityDDL, new SelectList(@ViewBag.CityDDL),new {style="Width:300px"})
                             @*  @Html.DropDownListFor(m=>m.cityDDL, new SelectList(Model.city), new  { style="Width:300px"})*@
                          </td>
                      </tr>
                       <tr>
                           <td style="width:200px">
                                @Html.LabelFor(m=>m.state)
                          </td>
                           <td style="width:300px">
                                @Html.DropDownListFor(m=>m.stateDDL, new SelectList(@ViewBag.StateDDL),new {style="Width:300px"})
                              @*  @Html.DropDownListFor(m=>m.stateDDL, new SelectList(Model.state), new  { style="Width:300px"})*@
                          </td>
                      </tr>
                  </table>
                  <input type="submit" value="Register Emp Information" style="text-align:center"/>
              </div>
   
            }
        </body>

这可能会对您有所帮助。http://code.msdn.microsoft.com/Cascading-DropDownList-in-833683f9

尝试实现本教程中给出的示例。

我在这里写了关于这个主题的博客:

http://jnye.co/Posts/12/creating-cascading-dropdownlists-using-mvc-4-and-jquery

从本质上讲,它使用 javascript 回发并检索每个更改的更新国家/地区列表。

@using (Html.BeginForm())
{
    <div>Select country:</div>
    <div>@Html.DropDownList("country", 
                            ViewBag.Countries as SelectList, 
                            "Please select", 
                            new { id = "country" })
    </div>
    <div>Select state:</div>
    <div>
        <select id="state" disabled="disabled"></select>
    </div>
    <input type="submit" value="Submit"/>
}

@section scripts
{
    <script type="text/javascript">
        $(function() {
            $('#country').on('change', function() {
                var stateDropdown = $('#state');
                //disable state drop down
                stateDropdown.prop('disabled', 'disabled');
                //clear drop down of old states
                stateDropdown.empty();
                //retrieve selected country
                var country = $(this).val();
                if (country.length > 0) {
                    // retrieve data using a Url.Action() to construct url
                    $.getJSON('@Url.Action("GetStates")', {
                        country: country
                    })
                    .done(function (data) {
                        //re-enable state drop down
                        stateDropdown.removeProp('disabled');
                        //for each returned state
                        $.each(data, function (i, state) {
                            //Create new option
                            var option = $('>option /<').html(state);
                            //append state states drop down
                            stateDropdown.append(option);
                        });
                    })
                    .fail(function (jqxhr, textStatus, error) {
                        var err = textStatus + ", " + error;
                        console.log("Request Failed: " + err);
                    });
                }
            });
        })
    </script>
}

当然,您必须更新GetDates()方法才能使用自己的数据源

public JsonResult GetStates(string country)
{
    var states = new List<string>();
    //TODO: You will need to update this code to supply your own data
    switch (country)
    {
        case "USA":
            states.Add("California");
            states.Add("Florida");
            states.Add("Ohio");
            break;
        case "UK":
            states.Add("London");
            states.Add("Essex");
            break;
        case "India":
            states.Add("Goa");
            states.Add("Punjab");
            break;
    }
    //Add JsonRequest behavior to allow retrieving states over http get
    return Json(states, JsonRequestBehavior.AllowGet);
}

也可以在这里找到这方面的演示:http://jnye.co/Demo/Jquery/cascading-dropdown-lists

最新更新