-->

建一个空MVC DropdownListFor用于级联子列表(Build an empty MVC

2019-08-01 20:28发布

我想建一个空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,空)

并取出//构建DROPDOWNLIST从控制器的型号?

谢谢

Answer 1:

研究发现,我认为是最好的,因为它没有任何服务调用的解决方案来构建dropdroplist空,这是强类型:

@Html.DropDownListFor(m => m.Model_Id, Enumerable.Empty<SelectListItem>(), HeelpResources.DropdownlistModelFirstRecord)


Answer 2:

以下是工作

@Html.DropDownListFor(m => m.Model_Id, **new SelectList(new List<string>()**));


Answer 3:

我个人有一点的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局部视图



文章来源: Build an empty MVC DropdownListFor for a Cascade Sub-List