【问题标题】:getting selected object from dropdownlist linked to a database - MVC3从链接到数据库的下拉列表中获取选定的对象 - MVC3
【发布时间】:2012-11-09 15:53:03
【问题描述】:

我是 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();
});
});

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

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

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);
    }
}
}

【问题讨论】:

  • 您能告诉我们您的路线以及您是如何调用 ModelList 方法的吗?
  • 对此感到抱歉。我是 MVC asp.net 和整个结构的新手。还在学习。我已经更新了 Jquery 类以及我的模型和视图。我希望它会有所帮助。另外,我忘记提及的代码的结果。
  • 你能告诉我们你的路线吗?我认为您的路线是问题所在。
  • 请问您所说的路由是什么意思?我以为我是通过 var URL = $('#CategoryFormID').data('makeListAction'); 调用该方法不是吗?
  • 我不知道这条路线是什么意思,我只是做了一个小研究,我现在正在研究它。很可能问题来自那里,但如果不是,我稍后会更新您。谢谢!

标签: c# asp.net-mvc-3 jquery


【解决方案1】:

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

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

【讨论】:

  • 天啊,一直以来!哈哈,非常感谢。我对这个问题感到非常沮丧。我几乎完全放弃了 MVC。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多