1

我是 MVC3 框架的新手。所以我正在练习并尝试学习如何使用 jquery 来创建级联下拉列表。我发现了 Rick Anderson 的这个样本:http: //blogs.msdn.com/b/rickandy/archive/2012/01/09/cascasding-dropdownlist-in-asp-net-mvc.aspx

因此,我尝试使用此示例自定义我自己的网站,以获得级联下拉列表。这是我的控制器:

private SelectList GetMakeSelectList()
    {
        var makeQry = from m in db.Car
                      orderby m.Make
                      select m.Make;
        return new SelectList(makeQry.ToArray(), "Make");
    }

    public ActionResult MakeList()
    {
        if (HttpContext.Request.IsAjaxRequest())
            return Json(GetMakeSelectList(), JsonRequestBehavior.AllowGet);

        return RedirectToAction("Categories");
    }

    public ActionResult ModelList(string Make)
    {
        string make = Make;
        var model = from s in db.Car
                     where s.Make == make
                     select s.Model;

        if (HttpContext.Request.IsAjaxRequest())
            return Json(new SelectList(
                            model.ToArray())
                       , JsonRequestBehavior.AllowGet);

        return RedirectToAction("Categories");
    }

    public ActionResult Categories()
    {
        return View();
    }

这是我的模型:

public class Car
{
    public int ID { get; set; }

    public String Make { get; set; }

    public String Model { get; set; }

    public decimal Price { get; set; }

    public String Edition { get; set; }

    public String Type { get; set; }

    public decimal Consumption { get; set; }

    public decimal Acceleration { get; set; }

    public decimal Horsepower { get; set; }

    public bool? Convertible { get; set; }
}
public class MovieDBContext : DbContext
{
    public DbSet<Car> Car { get; set; }
}

问题是:ModelList 方法中的 String Make 为空。所以我试图不在模型类中手动设置我的值,而只是在数据库中设置它们。

我的猜测是:SelectList(makeQry.ToArray(), "Make"),我使用的选定值的类型不是它所期望的。但我不知道如何传递查询的预期类型。

我正在为此使用 Jquery。我真的很感激任何帮助。

更新:这是视图:

@model IEnumerable<Cars.Models.Car>

<script src="@Url.Content("~/Scripts/GetMake.js")"></script>
<script src="@Url.Content("~/Scripts/makeModel.js")"></script>
<link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/CategoriesStyle.css")" />

@using (Html.BeginForm("Categories", "Category", FormMethod.Post, 
new { id = "CategoryFormID", 
    data_modelListAction = @Url.Action("ModelList"),
    data_makeListAction = @Url.Action("MakeList")})) {

<div id="content">
    <fieldset>
        <legend>Advanced Search</legend> 

        <div class="myform">

            <p>Search the car you're looking for in all details you can imagine right here!</p>

            <div id="MakeDivID">
                <label>Make</label>
                <select id="MakeID" name="Make"></select>
            </div>

            <div id="ModelDivID">
                <label>Model</label>
                <select id="ModelID" name="Model"></select>
            </div>



            <button type="submit" id="SubmitID">Search</button>
        </div>
    </fieldset>
</div>

}

这将是我的 Jquery,我在其中填充保管箱并调用方法:

这是 GetMake.js

$(function () {
var URL = $('#CategoryFormID').data('makeListAction');
$.getJSON(URL, function (data) {
    var items = "<option>Select a Car Make</option>";
    $.each(data, function (i, make) {
        if (make.Text.indexOf("\'") > -1) {
            s = make.Text;
            alert(s + ": Country.Value cannot contain \'")
        }
        items += "<option>" + make.Text + "</option>";
    });
    $('#MakeID').html(items);
});
});

这是makeModel.js:

$(function () {
$('#ModelDivID').hide();
$('#SubmitID').hide();
$('#MakeID').change(function () {
    var URL = $('#CategoryFormID').data('modelListAction');
    $.getJSON(URL + '/' + $('#MakeID').val(), function (data) {
        var items = '<option>Select a Model</option>';
        $.each(data, function (i, model) {
            items += "<option>" + model.Text + "</option>";
            // state.Value cannot contain ' character. We are OK because state.Value = cnt++;
        });
        $('#ModelID').html(items);
        $('#ModelDivID').show();
    });
});
$('#ModelID').change(function () {
    $('#SubmitID').show();
});
});

第二次更新:我忘了提到我得到的结果不是我想要的。结果是第一个保管箱出现,其中包含所有正确的值,当我单击其中一个时,第二个保管箱出现但它是空的,因为我没有传递 Make 对象在 ModelList() 中为空。

第三次更新:这是你问的我的路线。我希望这就是你要找的。

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Cars
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode, 
// visit http://go.microsoft.com/?LinkId=9394801

public class MvcApplication : System.Web.HttpApplication
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );

    }

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        // Use LocalDB for Entity Framework by default
        Database.DefaultConnectionFactory = new SqlConnectionFactory(@"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }
}
}
4

1 回答 1

0

看过您的路线后,我认为这是您的问题:

public ActionResult ModelList(string Make)

您的路线说必须调用参数id,以便可以对其进行映射(这是默认路由..这就是我想仔细检查的原因)。

routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // <---- This part here says {id}
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

要解决您的问题,您可能只需将 ModelList 函数更改为:

public ActionResult ModelList(string id) {
    string make = id; // assign the string id to the make variable
于 2012-11-09T07:53:03.640 回答