使用MVC3 & 3级下拉列表级联LinqSql

发布于 2024-11-27 10:41:55 字数 557 浏览 4 评论 0原文

我有 3 个下拉列表,我想用级联制作 3 个下拉列表。我使用 LinqSql 作为数据库。

我有 3 个表 Product(id,name)、Design(id,master_id,name)、Model(id,design_id,name) master_id 绑定到产品(id),design_id 绑定到设计(id)..

我想创建一个下拉列表,它将显示产品,并且当我选择一个产品时,它将使设计下拉列表启用,否则它将保持禁用状态..也在这里这是我无法解决的棘手部分,我需要在这里创建第三个下拉菜单,该下拉菜单通常会被禁用,直到选择设计为止。

他们每个人都会填充与他们绑定的较低下拉列表。就像; 产品将启用并填充设计, 设计将启用并填充模型。 我可以用 2 个下拉菜单来完成,但是当涉及到 3 个下拉菜单时,我真的陷入了困境(大脑冻结)..

我已经检查了其他问题,无法为自己找到任何解决方案。正如我所说,我使用 LinqSql,我需要一个关于 3 个级联下拉列表的解决方案来实现此类数据到达。

已经感谢你所做的一切!如果你能解释模型-视图-控制器部分和参数以及为什么使用它们,那就太棒了。我是这个 MVC3 的初学者。

I have 3 dropdownlist i wanna make 3 dropdownlist with cascade. I am using LinqSql for database..

I have 3 tables Product(id,name), Design(id,master_id,name), Model(id,design_id,name)
master_id bound to Product(id), design_id bound to Design(id)..

I want to create one dropdown which is gonna show Products and than when i choose a product its gonna make Design dropdown enabled else it will stay disabled.. also here is the tricky part that i couldnt solve and i need great explanation in here creating 3rd dropdown which is gonna be disabled normally till a Design is chosen.

Each of them gonna populate a lower dropdownlist bound to them.Its like;
Product gonna enable and populate Design,
Design gonna enable and populate Model.
I can do it with 2 dropdowns but when it comes to 3 dropdown i stuck really badly im on (brain-freeze)..

I already checked the other questions couldnt find any solution for my self. As i said im using LinqSql i need a solution about 3 cascadingdropdown list for this type of data reach.

thanks already for anything u can do! and if u can explain Model-View-Controller partials and the parameters and why you use them that would be awesome. Iam kinda beginner at this MVC3.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

泪之魂 2024-12-04 10:41:55

我会这样处理这个问题:

首先,在控制器中,我们将设置以下方法:

public JsonResult GetDesignsForProduct(int productId)
{
  // Instantiate our context and do whatever goo we need to select the objects we want
  using (MyDatabaseContext ctx = new MyDatabaseContext())
  {
     return Json(ctx.Designs.Where(d => d.master_id == productId).ToList(), JsonRequestBehavior.AllowGet);
  }
}

public JsonResult GetModelsForDesign(int designId)
{
  // Instantiate our context and do whatever goo we need to select the objects we want
  using (MyDatabaseContext ctx = new MyDatabaseContext())
  {
     return Json(ctx.Models.Where(d => d.design_id == designId).ToList(), JsonRequestBehavior.AllowGet);
  }
}

我在这里打开了“get”;如果您的数据包含敏感信息 - 用户名/电子邮件地址、其他专有或受法律保护的数据等 - 您可以将其更改为仅允许“发布”,并相应地修改您的 Javascript。请参阅 Phil Haack 的文章

另外,如果您预计此数据会频繁更改,这些方法将根据您的应用程序的缓存设置默认缓存它。您可以在该方法上添加一个 OutputCache 属性来更改此行为。

然后,在视图中您将拥有一些 AJAX 管道,如下所示:

function LoadDesigns() {
    // Get the currently-selected value in our Product dropdown
    var prod = $("#Product").val();

    // Call our controller method and process the list of Design objects
    $.getJSON('@Url.Content("~/ControllerName/GetDesignsForProduct")', { productId: prod },
        function (designs) {
            $("#Design").empty();
            $.each(designs, function (i, c) {
                $("#Design").append(
                    $('<option></option>').val(c.id).html(c.name)
                );
            });
    });
}

function LoadModels() {
    // Get the currently-selected value in our Design dropdown
    var des = $("#Design").val();

    // Call our controller method and process the list of Model objects
    $.getJSON('@Url.Content("~/ControllerName/GetModelsForDesign")', { designId: des },
        function (models) {
            $("#Model").empty();
            $.each(models, function (i, c) {
                $("#Model").append(
                    $('<option></option>').val(c.id).html(c.name)
                );
            });
    });
}

最后,定义所有三个下拉列表如下所示:

@Html.DropDownList("Product", productSelectList, new { onchange = "LoadDesigns()" })
@Html.DropDownList("Design", null, new { onchange = "LoadModels()" })
@Html.DropDownList("Model")

不要忘记,HTML 帮助程序实际上只是生成底层 HTML 的快捷方式,在 Razor 中,您经常直接进入 HTML,而不是搞乱帮助程序。所以你可以很容易地把它们写成:

<select id="Product" onchange="LoadDesigns()">
  @foreach (var prod in products) {
    <option value="@prod.id">@prod.name</option>
  }
</select>

<select id="Design" onchange="LoadModels()"></select>

<select id="Model"></select>

I would approach the problem something like this:

First, in the controller, we'll set up have the following methods:

public JsonResult GetDesignsForProduct(int productId)
{
  // Instantiate our context and do whatever goo we need to select the objects we want
  using (MyDatabaseContext ctx = new MyDatabaseContext())
  {
     return Json(ctx.Designs.Where(d => d.master_id == productId).ToList(), JsonRequestBehavior.AllowGet);
  }
}

public JsonResult GetModelsForDesign(int designId)
{
  // Instantiate our context and do whatever goo we need to select the objects we want
  using (MyDatabaseContext ctx = new MyDatabaseContext())
  {
     return Json(ctx.Models.Where(d => d.design_id == designId).ToList(), JsonRequestBehavior.AllowGet);
  }
}

I've turned on "get" here; if your data contains sensitive information - user names/e-mail addresses, other proprietary or legally protected data, etc. - you can change this to only allow "post", and modify your Javascript accordingly. See Phil Haack's article.

Also, if you expect this data to change frequently, these methods will cache it by default according to your application's cache settings. You can add an OutputCache attribute on the method to alter this behavior.

Then, in the view you'll have some AJAX plumbing, something like this:

function LoadDesigns() {
    // Get the currently-selected value in our Product dropdown
    var prod = $("#Product").val();

    // Call our controller method and process the list of Design objects
    $.getJSON('@Url.Content("~/ControllerName/GetDesignsForProduct")', { productId: prod },
        function (designs) {
            $("#Design").empty();
            $.each(designs, function (i, c) {
                $("#Design").append(
                    $('<option></option>').val(c.id).html(c.name)
                );
            });
    });
}

function LoadModels() {
    // Get the currently-selected value in our Design dropdown
    var des = $("#Design").val();

    // Call our controller method and process the list of Model objects
    $.getJSON('@Url.Content("~/ControllerName/GetModelsForDesign")', { designId: des },
        function (models) {
            $("#Model").empty();
            $.each(models, function (i, c) {
                $("#Model").append(
                    $('<option></option>').val(c.id).html(c.name)
                );
            });
    });
}

Finally, define all three drop-downs as follows:

@Html.DropDownList("Product", productSelectList, new { onchange = "LoadDesigns()" })
@Html.DropDownList("Design", null, new { onchange = "LoadModels()" })
@Html.DropDownList("Model")

Don't forget that the HTML helpers are really just shortcuts to generate the underlying HTML, and in Razor you frequently just go straight to HTML instead of messing with the helpers. So you could just as easily write these as:

<select id="Product" onchange="LoadDesigns()">
  @foreach (var prod in products) {
    <option value="@prod.id">@prod.name</option>
  }
</select>

<select id="Design" onchange="LoadModels()"></select>

<select id="Model"></select>
澜川若宁 2024-12-04 10:41:55

忘记设置我完成的工作..人们可能想看看它是如何发生的..
这是我的:

View + Jquery

$(function () {
    $("select#Design").attr('disabled', 'true');
    $("select#Model").attr('disabled', 'true');

    $("select#Product").click(function () {
        var prod = $("select#Product option:selected").val();
        if (prod == "" || prod == 0) {
            $("select#Design").attr('disabled', 'true');
            $("select#Model").attr('disabled', 'true');
        } else {
            $.getJSON('@Url.Content("~/Admin/GetDesigns/")', { productId: prod }, function (data) {
                $("select#Design").empty();
                $("select#Model").empty();
                $.each(data, function (i, c) {
                    $('select#Design').append('<option value="' + c.Value + '">' + c.Text + '</option>');
                })
                $("select#Design").removeAttr('disabled');
                $("select#Design option:first").attr('selected', 'selected');

                var des = $("select#Design option:selected").val();
                if (des == "" || des == 0) {
                    $("select#Model").attr('disabled', 'true');
                } else {
                    $.getJSON('@Url.Content("~/Admin/GetModels/")', { designId: des }, function (data) {
                        $("select#Model").empty();
                        $.each(data, function (i, c) {
                            $('select#Model').append('<option value="' + c.Value + '">' + c.Text + '</option>');
                        })
                        $("select#Model").removeAttr('disabled');
                        $("select#Model option:first").attr('selected', 'selected');
                     })
                  }
               })
            }
         })
     })

我使用 Jquery 这种方式来填充所有下拉列表并选择第一个元素作为默认选择的原因!当我从第一个下拉列表中选择一个元素时,其他两个下拉列表开始填充自己并选择它们的第一个元素作为默认选择。相同的代码可用于其他下拉列表单击功能,如下所示:

            $("select#Design").click(function () {
                var des = $("select#Design option:selected").val();
                if (des == "" || des == 0) {
                    $("select#Model").attr('disabled', 'true');
                } else {
                    $.getJSON('@Url.Content("~/Admin/GetModels/")', { designId: des }, function (data) {
                        $("select#Model").empty();
                        $.each(data, function (i, c) {
                            $('select#Model').append('<option value="' + c.Value + '">' + c.Text + '</option>');
                        })
                        $("select#Model").removeAttr('disabled');
                        $("select#Model option:first").attr('selected', 'selected');
                    })
                }
           });

查看

@using (Html.BeginForm("Index", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
    <tr>
        <td style="background-color:#e8eef4;" rowspan="3">
        </td>
        <td style="width:190px; background-color:#e8eef4;">
            @Html.DropDownList("Product", (SelectList)ViewData["ProductList"], "Please Select Product", new { style = "width:190px; padding:4px; margin:4px;" })
        </td>
        <td rowspan="3" style="width:400;">
        </td>
        <td style="background-color:#e8eef4;">
        </td>
        <td style="background-color:#e8eef4;" rowspan="3">
        </td>
    </tr>
    <tr>
        <td style="background-color:#e8eef4;">
            <select id="Design" style="width:190px; padding:4px; margin:4px;">
            <option label="Please Select Design" selected="selected"></option>
            </select>
        </td>
        <td style="background-color:#e8eef4;">
        </td>
    </tr>
    <tr>
        <td style="background-color:#e8eef4;">
            <select id="Model" style=" width:190px; padding:4px; margin:4px;">
            <option label="Please Select Model"></option>
            </select>
        </td>
        <td style="background-color:#e8eef4;">
        </td>
    </tr>
</table>
}

只是因为我使用 linqtosql 并且我太懒了制作一个存储库..
这是我的 CONTROLLER

public class AdminController : Controller
{
    public linqVipDataContext db = new linqVipDataContext();

    //
    // GET: /Admin/
    public ActionResult Index()
    {
        IEnumerable<SelectListItem> ProductItems = db.Products.AsEnumerable().Select(c => new SelectListItem()
        {
            Text = c.name,
            Value = c.id.ToString(),
            Selected = true,
        });
        SelectList prod = new SelectList(ProductItems, "Value", "Text");
        ViewBag.ProductList = prod;
        return View();
    }


    //
    //Fill the Design List..
    public JsonResult GetDesigns(int productId)
    {
        /*var data = dbs.Designs.Where(d => d.master_id == productId).ToList();*/

        IEnumerable<SelectListItem> DesignItems = db.Designs.Where(c => c.master_id == productId).AsEnumerable().Select(c => new SelectListItem()
        {
            Text = c.name,
            Value = c.id.ToString()
        });
        SelectList des = new SelectList(DesignItems, "Value", "Text");
        return Json(des, JsonRequestBehavior.AllowGet);
    }

    //
    //Fill the Model List..
    public JsonResult GetModels(int designId)
    {   
        /*This code down here! Doesnt work and says it's type is unknown*/
        /*var data = dbs.Models.Where(d => d.design_id == designId).ToList();*/

        /*For that reason im using this code*/
        IEnumerable<SelectListItem> ModelItems = db.Models.Where(d => d.design_id == designId).AsEnumerable().Select(c => new SelectListItem()
        {
            Text = c.name,
            Value = c.id.ToString()
        });
        SelectList mods= new SelectList(ModelItems, "Value", "Text");
        return Json(mods, JsonRequestBehavior.AllowGet);
    }

Json 需要将 Value 和 Text 2 参数分开来创建选择列表选项。所以我必须以这种方式返回我的值。

我发布这个原因是因为我在你的代码中发现了一些故障,再次向我展示了它给出的这个解决方案我的想法并让我解决了所有问题,所以这是完全有效的代码..再次Ty。希望它有用。

Forget to set my finished work.. People may wanna see how it happens..
Here is my:

View + Jquery

$(function () {
    $("select#Design").attr('disabled', 'true');
    $("select#Model").attr('disabled', 'true');

    $("select#Product").click(function () {
        var prod = $("select#Product option:selected").val();
        if (prod == "" || prod == 0) {
            $("select#Design").attr('disabled', 'true');
            $("select#Model").attr('disabled', 'true');
        } else {
            $.getJSON('@Url.Content("~/Admin/GetDesigns/")', { productId: prod }, function (data) {
                $("select#Design").empty();
                $("select#Model").empty();
                $.each(data, function (i, c) {
                    $('select#Design').append('<option value="' + c.Value + '">' + c.Text + '</option>');
                })
                $("select#Design").removeAttr('disabled');
                $("select#Design option:first").attr('selected', 'selected');

                var des = $("select#Design option:selected").val();
                if (des == "" || des == 0) {
                    $("select#Model").attr('disabled', 'true');
                } else {
                    $.getJSON('@Url.Content("~/Admin/GetModels/")', { designId: des }, function (data) {
                        $("select#Model").empty();
                        $.each(data, function (i, c) {
                            $('select#Model').append('<option value="' + c.Value + '">' + c.Text + '</option>');
                        })
                        $("select#Model").removeAttr('disabled');
                        $("select#Model option:first").attr('selected', 'selected');
                     })
                  }
               })
            }
         })
     })

reason i use Jquery this way to fill all dropdowns and select first elements as default selection! When i choose an element from first dropdown the other two dropdowns starts to fill themselves and select their first element as default selection.. same code can be used for other dropdowns click function just like this:

            $("select#Design").click(function () {
                var des = $("select#Design option:selected").val();
                if (des == "" || des == 0) {
                    $("select#Model").attr('disabled', 'true');
                } else {
                    $.getJSON('@Url.Content("~/Admin/GetModels/")', { designId: des }, function (data) {
                        $("select#Model").empty();
                        $.each(data, function (i, c) {
                            $('select#Model').append('<option value="' + c.Value + '">' + c.Text + '</option>');
                        })
                        $("select#Model").removeAttr('disabled');
                        $("select#Model option:first").attr('selected', 'selected');
                    })
                }
           });

View

@using (Html.BeginForm("Index", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
    <tr>
        <td style="background-color:#e8eef4;" rowspan="3">
        </td>
        <td style="width:190px; background-color:#e8eef4;">
            @Html.DropDownList("Product", (SelectList)ViewData["ProductList"], "Please Select Product", new { style = "width:190px; padding:4px; margin:4px;" })
        </td>
        <td rowspan="3" style="width:400;">
        </td>
        <td style="background-color:#e8eef4;">
        </td>
        <td style="background-color:#e8eef4;" rowspan="3">
        </td>
    </tr>
    <tr>
        <td style="background-color:#e8eef4;">
            <select id="Design" style="width:190px; padding:4px; margin:4px;">
            <option label="Please Select Design" selected="selected"></option>
            </select>
        </td>
        <td style="background-color:#e8eef4;">
        </td>
    </tr>
    <tr>
        <td style="background-color:#e8eef4;">
            <select id="Model" style=" width:190px; padding:4px; margin:4px;">
            <option label="Please Select Model"></option>
            </select>
        </td>
        <td style="background-color:#e8eef4;">
        </td>
    </tr>
</table>
}

Just cause im using linqtosql and im too lazy to make a repository..
This is my CONTROLLER

public class AdminController : Controller
{
    public linqVipDataContext db = new linqVipDataContext();

    //
    // GET: /Admin/
    public ActionResult Index()
    {
        IEnumerable<SelectListItem> ProductItems = db.Products.AsEnumerable().Select(c => new SelectListItem()
        {
            Text = c.name,
            Value = c.id.ToString(),
            Selected = true,
        });
        SelectList prod = new SelectList(ProductItems, "Value", "Text");
        ViewBag.ProductList = prod;
        return View();
    }


    //
    //Fill the Design List..
    public JsonResult GetDesigns(int productId)
    {
        /*var data = dbs.Designs.Where(d => d.master_id == productId).ToList();*/

        IEnumerable<SelectListItem> DesignItems = db.Designs.Where(c => c.master_id == productId).AsEnumerable().Select(c => new SelectListItem()
        {
            Text = c.name,
            Value = c.id.ToString()
        });
        SelectList des = new SelectList(DesignItems, "Value", "Text");
        return Json(des, JsonRequestBehavior.AllowGet);
    }

    //
    //Fill the Model List..
    public JsonResult GetModels(int designId)
    {   
        /*This code down here! Doesnt work and says it's type is unknown*/
        /*var data = dbs.Models.Where(d => d.design_id == designId).ToList();*/

        /*For that reason im using this code*/
        IEnumerable<SelectListItem> ModelItems = db.Models.Where(d => d.design_id == designId).AsEnumerable().Select(c => new SelectListItem()
        {
            Text = c.name,
            Value = c.id.ToString()
        });
        SelectList mods= new SelectList(ModelItems, "Value", "Text");
        return Json(mods, JsonRequestBehavior.AllowGet);
    }

Json requires Value and Text 2 param seperated for creating a selectlist option.. So i must return my value that way..

I posted this cause i found some breakdowns at ur code, ty again for showing me this solution it gave me the idea and allowed me to solve all problems so this is the fully working code.. Ty again. Hope its usefull.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文