我对来自 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<SelectListItem> BerryList { get; set; }
    public IEnumerable<SelectListItem> BerryColorList { get; set; }

    [Display(Name = "Berry")]
    public byte? Berry { get; set; }

    [Display(Name = "BerryColor")]
    public byte? BerryColor { get; set; }
}

我的控制器是这样的,我需要根据浆果的类型选择颜色。假设 Avacado 选择全部,Banana 则选择第 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" }))
{

<div class="form-group">
    @Html.LabelFor(m => m.Berry, new { @class = "col-md-2 control-label" })
    <div class="col-md-10" >
        @Html.DropDownListFor(m => m.Berry, Model.BerryList, "Please Select")
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(m => m.BerryColor, new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownListFor(m => m.BerryColor, Model.BerryColorList, "Please Select")
    </div>
</div>

}

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

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

有帮助吗?

解决方案

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

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

有关如何在实践中实现这一目标的帮助,请参阅 MVC 4 中的级联 DropDownList. 。您可以根据您的需要找到类似的示例。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top