40

我想建立一个空的 Dropdownlistfor 来接收先前 Dropdownlisfor 选择的结果:

实际观点:

    <div id="makes">
        @Html.DropDownListFor(m => m.Make_Id, Model.MakeList, HeelpResources.DropdownlistMakeFirstRecord)
    </div>
    <div id="models">
        @Html.DropDownListFor(m => m.Model_Id, Model.ModelList, HeelpResources.DropdownlistModelFirstRecord)
    </div>        

实际的控制器(为了工作,我必须构建一个空的 SelectedList 但这样做似乎很奇怪):

   public virtual ActionResult Create()
    {
        // Build the Dropdownlist for the Makes
        var makesDto = _makeService.ListAllMakes();
        var makesViewModel = Mapper.Map<IList<MakeDto>, IList<MakeViewModel>>(makesDto);

        // Build the Dropdownlist for the Models
        var makeId = -1;
        var modelsDto = _modelService.ListModelByMake(makeId);
        var modelsViewModel = Mapper.Map<IList<ModelDto>, IList<ModelViewModel>>(modelsDto);

        // Build the ViewModel to return to the View
        CreateAdViewModel viewModel = new CreateAdViewModel();
        viewModel.MakeList = new SelectList(makesViewModel, "ID", "Name");
        viewModel.ModelList = new SelectList(modelsViewModel, "ID", "Name"); 

        return View(viewModel);
    }

有没有办法构建这样的东西:@Html.DropDownListFor(m => m.Model_Id, null)

并从控制器中删除 // Build the Dropdownlist for the Models?

谢谢

4

3 回答 3

121

找到了一个我认为最好的解决方案,因为它没有服务调用来构建 dropdroplist 空并且它是强类型的:

@Html.DropDownListFor(m => m.Model_Id, Enumerable.Empty<SelectListItem>(), HeelpResources.DropdownlistModelFirstRecord)
于 2012-10-25T13:30:40.220 回答
2

以下工作

@Html.DropDownListFor(m => m.Model_Id, **new SelectList(new List<string>()**));
于 2016-04-19T09:10:12.853 回答
0

就我个人而言,我会用一点 jQuery 和一个额外的局部视图来做到这一点。您的表单可能如下所示:

<div id="makes">
        @Html.DropDownListFor(m => m.Make_Id, Model.MakeList, HeelpResources.DropdownlistMakeFirstRecord)
</div>
<div id="models">

</div>

<script type="text/javascript">
$(function(){
   $("#Make_Id").change(function(){
       $("#models").load("/Controller_Name/GetModels/" + this.val());
   }
});
</script>  

然后在你的控制器中:

public ActionResult GetModels(int id)
{
   ViewBag.DdlModels = new SelectList(rep.GetModelsForCar(id), "Id", "Name");
   return PartialView();
}

然后将您的下拉列表粘贴在 GetModels 部分视图中

于 2012-10-24T15:43:27.543 回答