使用MVC5,Ajax,C#和MSSQL Server级联DropdownList

来自Windows窗体和3层架构的MVC我很陌生。

我试图找出使用从数据库填充的级联下拉列表(DDL)。 我正在使用MS SQL Server 2012,VS 2013

目前我正在处理用户问卷,用户可以从DDL的多个答案中进行选择。 取决于一些选择,我需要在下一个问题上更改答案(再次DDL)。

数据库:

DDLStacks

 StackId | StackName 1 | Berry 2 | BerryColor 3 .... 

DDLStackContents (SCId堆栈内容id,索引目的)

 SCId | StackId | GroupId | Key | Value -------------------------------------- 1 | 1 | Null | 1 | Grape 2 | 1 | Null | 2 | Avocado 3 | 1 | Null | 3 | Banana 4 | 2 | Null | 1 | Yellow 5 | 2 | Null | 2 | Green 6 | 2 | 1 | 3 | Red 7 | 2 | 1 | 4 | Orange 8... 

程序:

  CREATE PROCEDURE [dbo].[spDLLSelect] @p_StackName_in VARCHAR(20), @p_GroupId_in Int = null AS BEGIN SELECT [Key],Value FROM DDLStackContents WHERE StackID IN (SELECT StackId FROM DDLStacks WHERE StackName = @p_StackName_in) AND (GroupId = @p_GroupId_in OR @p_GroupId_in IS null) Order By [Key] END 

正如您所看到的, DDLStacks存在问题, DDLStackContents为该问题提供了可能的答案。

如果有一个组,我们可以只从该组中选择答案,否则选择特定堆栈的所有答案。

现在我创建了一个ADO.NET实体数据模型来访问spDLLSelect。

现在我的水果模型就是这个

 public class FruitModel { public IEnumerable BerryList { get; set; } public IEnumerable BerryColorList { get; set; } [Display(Name = "Berry")] public byte? Berry { get; set; } [Display(Name = "BerryColor")] public byte? BerryColor { get; set; } } 

我的控制器是这个,我需要选择颜色取决于浆果的类型。 如果Avacado选择全部,如果香蕉只是第1组。

 public class HomeController : Controller { public ActionResult Index() { CherryEntities db = new CherryEntities(); var model = new FruitModel(); model.BerryList = new SelectList(db.spDLLSelect("Berry", null), "Key", "Value"); //model.BerryColorList = new SelectList(db.spDLLSelect("BerryColor", null), "Key", "Value"); //model.BerryColorList = new SelectList(db.spDLLSelect("BerryColor", 1), "Key", "Value"); return View(model); } } 

这是我的观点:

 @using (Html.BeginForm("Register2", "Account", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { 
@Html.LabelFor(m => m.Berry, new { @class = "col-md-2 control-label" })
@Html.DropDownListFor(m => m.Berry, Model.BerryList, "Please Select")
@Html.LabelFor(m => m.BerryColor, new { @class = "col-md-2 control-label" })
@Html.DropDownListFor(m => m.BerryColor, Model.BerryColorList, "Please Select")
}

这是我的基本编码,我已经尝试了各种方法来使其工作,我希望看到使用ajax STRONGLY Typed代码执行此操作的正确方法。

可能正在使用局部视图? 有什么想法吗?

您已经有一个模型,您的视图是强类型的。 您需要做的就是在下拉列表中添加更改事件(有关更多信息,请参阅下面的参考链接)。 在更改事件中,您可以根据所选值加载值,例如,如果选择了Berry,您将需要获取Berry的相应值,即Grape,Avocado。

您可以使用JavaScript加载值,这在您拥有大量数据时非常有用。 或者您可以使用所有数据预加载视图,在这种情况下,您只需根据在UI上选择的问题过滤答案。

有关如何在实践中实现此目的的帮助,请参阅MVC 4中的Cascading DropDownList 。 您可以根据自己的需要找到类似的示例。