MVC 5选择列表 - 用户输入

时间:2017-01-09 05:09:21

标签: c# asp.net-mvc select combobox

我使用以下内容根据国家/地区选择生成省份下拉列表:

  <select id="Province" name="Province"  class="form-control  input-sm">
    @{ 
       string[] provinces = ViewBag.ProvincesForSelectedCountry;
       string selectedProvinceName = null;
     }
    @{
       if (Model != null && !String.IsNullOrEmpty(Model.Province))
       {
          selectedProvinceName = Model.Province;
       } 
       else 
       {
          selectedProvinceName = ConfigData.DefaultProvinceName;
       }
     }
    @foreach (var anEntry in provinces)
    {
       string selectedTextMark = anEntry == selectedProvinceName 
          ? "selected=\"selected\"" 
          : String.Empty;
       <option value="@(anEntry)" @(selectedTextMark)>@(anEntry)</option>
    }
  </select>

挑战在于我没有其他国家的省(州)名单!有没有办法允许用户输入省名?像一个组合框。

1 个答案:

答案 0 :(得分:0)

我必须使用Knockout-Kendo组合框来完成,这是解决方案: 控制器:

   public ActionResult Index()
        {
            ViewBag.CountryID = new SelectList(db.Countries, "ID", "Name", "34");
.....

   public JsonResult GetState(int? id)
        {
            if (id == null)
            {   id = 34;  }
            var data =   db.States.Where(x => x.CountryID == id)
                    .Select( x =>
                            new
                            {
                                ID = x.ID,
                                Name = x.Name
                            }).ToList();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

在视图中:

@Html.DropDownList("Country", ViewBag.CountryID as SelectList, "Select...",
 new { onchange = "UpdateProvinces();" })
<input data-bind="kendoComboBox: { dataTextField: 'Name', dataValueField: 'ID',
 data: choices, value: selectedChoice }" />

这是JavaScript:

function UpdateProvinces() {
        var countryId = $("#Country  option:selected").val();
        $.getJSON("/Home/GetState/" + countryId,
            null,
            function (data) {
                objVM.choices(data);
            });
    }
    function ItemViewModel(arg) {
        arg = 34;
        var self = this;
        this.choices = ko.observableArray([]),
            $.ajax({
                type: "GET",
                url: '@Url.Action("GetState", "Home")',
                contentType: "application/json; charset=utf-8",
                data: { id: arg },
                dataType: "json",
                success: function (data) {
                    self.choices(data);
                },
                error: function (err) {
                    alert(err.status + " : " + err.statusText);
                }
            });
        var selectedChoice = {
            ID: self.ID,
            Name: self.Name
        };
        self.selectedChoice = ko.observable();
    }
    var objVM = new ItemViewModel();
    ko.applyBindings(objVM);

修改

另一种方法是使用Telerik MVC UI Combobox http://demos.telerik.com/aspnet-mvc/combobox/cascadingcombobox