簡體   English   中英

MVC 4 Ajax DropDownList

[英]MVC 4 Ajax DropDownList

表單上有兩個DropDownLists。

如果用戶在第一個DropDownList中選擇一個地區,則在第二個DropDownList中應該只有與該地區相關的城市。

我已經嘗試過在StackOverflow上找到的解決方案,但是由於我對jQuery和MVC的初學知識,我失敗了。 也許我的模型/控制器與其他模型/控制器之間有區別,這些DropDownLists已經存在,並且應該使用Ajax對其進行動態更改。

HTML

<div class="form-group col-sm-4">
    @Html.LabelFor(m => m.Company.Region.Name)
    @Html.DropDownList("region", Model.Regions, new { @class = "form-control" ,@id = "Region_drop" })
</div>

<div class="form-group col-sm-4">
    @Html.LabelFor(m => m.Company.City.Name)
    @Html.DropDownList("city", Model.Cities, new { @class = "form-control" ,@id = "City_drop" })
</div>

控制者

[Authorize]
public ActionResult AddCompany()
{
    CompanyModel company = new CompanyModel();
    SelectList regions = new SelectList(db.Regions, "Id", "Name");
    SelectList cities = new SelectList(db.Cities, "Id", "Name");

    AddCompanyViewModel acvm = new AddCompanyViewModel
    {
        Regions = regions,
        Cities = cities,
    };

    return View(acvm);
}

模型

public class RegionModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Display(Name = "Регион")]
    [Required]
    public string Name { get; set; }

    public IEnumerable<CompanyModel> Companies { get; set; }
    public IEnumerable<CityModel> Cities { get; set; }
}

public class CityModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Display(Name = "Город")]
    [Required]
    public string Name { get; set; }

    public int RegionId { get; set; }
    public RegionModel Region { get; set; }

    public IEnumerable<CompanyModel> Companies { get; set; }
}

更新:我嘗試編寫輔助ActionResult以便從數據庫獲取數據

[HttpPost]
public ActionResult getCitiesAction(int provinceId)
{
    var cities = db.Cities.Where(a => a.RegionId == provinceId).Select(a => "<option value='" + a.Id + "'>" + a.Name + "'</option>'");

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

然后根據其他解決方案之一的建議添加一些JS:

$("#Region_drop").change(function () {
  $.ajax({
    url: "getCitiesAction",
    type: "post",
    data: {
      provinceId: $("#Region_drop").val()
    }
  }).done(function (response) {
    $("#City_drop").html(response);
  });
});

在瀏覽器中運行此命令並創建一些斷點后,它會顯示區域ID,但是在調用ajax之后,該函數就會消失。

盡管您的代碼可以工作(除了會在選項文本后添加一個額外的'作為后綴, 但是將UI標記與生成數據的C#代碼混合並不是一個好主意 。使用當前代碼,您的action方法將生成所需的字符串)呈現選項。

我建議不要在操作方法中為選項標記構建字符串。 返回一個json數組。 這樣,如果要使用相同的操作方法呈現表行/ div /列表項的列表,則可以使用相同的方法。 從服務器傳輸的有效負載也更少。

[HttpPost]
public ActionResult getCitiesAction(int provinceId)
{
    var cities = db.Cities
                   .Where(a => a.RegionId == provinceId)
                   .Select(a => new SelectListItem { Value=a.Id.ToString(), Text=a.Name})
                   .ToList()

    return Json(cities);
}

現在,在您的ajax done事件中,遍歷此數組並創建一個選項項,設置text和value屬性值並將其添加到SELECT元素

).done(function (response) {
    $("#City_drop").empty();
    $.each(response,function(i,item)
    {
        $("#City_drop").append($("<option>").text(item.Text).val(item.Value));
    });   
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM