DropDownListFor选定值的问题

时间:2013-06-21 16:04:49

标签: asp.net-mvc-4 entity-framework-5

我对MVC相当新(好吧很新)。我正在尝试创建一个级联下拉列表,我也可以在其中预选一个值。

我大部分时间都在这上面度过,但并没有真正走得太远。我看了很多资源,虽然最有用的是:

http://www.deliveron.com/blog/post/Creating-a-Cascading-Dropdown-in-ASPnet-MVC-3-and-jQuery.aspx - 我大量使用了这个并且让我自己的版本正常工作,我无法在那里工作。

http://odetocode.com/blogs/scott/archive/2013/03/11/dropdownlistfor-with-asp-net-mvc.aspx - 一般的过分。

MVC DropDownList SelectedValue not displaying correctly - 这里有一个非常好的例子,遵循视图模型方法,但由于某种原因它似乎对我不起作用。

到目前为止我得到的是:

型号:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;

    namespace BLPrototype.Models
    {
        public class VehicleModels
        {
            public List<vehicle_make> getVehicleMakeList()
            {
                using (var db = new BLEntities())
                {
                    List<vehicle_make> vmk = db.vehicle_make.OrderBy(r => r.vmk_name).ToList();
                    return vmk;
                }
            }

            public List<vehicle_group> getVehicleModelList(string vmk_id)
            {
                using (var db = new BLEntities())
                {
                    List<vehicle_group> vmo = db.vehicle_group.Where(v => v.vg_vmk_id == vmk_id).OrderBy(r => r.vg_name).ToList();

                    return vmo;
                }
            }

        }

        public class vmCatalogue1
        {
            public string Title { get; set; }

            [Display(Name = "Select a make")]
            public IEnumerable<SelectListItem> selectVehicleMake { get; set; }
            [Display(Name = "Select a model")]
            public IEnumerable<SelectListItem> selectVehicleModel { get; set; }

        }

    }

控制器:

using BLPrototype.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BLPrototype.Controllers
{
    public class TestController : Controller
    {
        //
        // GET: /Test/

        public ActionResult Index()
        {
            VehicleModels vm = new VehicleModels();
            var model = new vmCatalogue1();

            //Which is better and why?
            model.selectVehicleMake = vm.getVehicleMakeList().Select(x => new SelectListItem { Value = x.vmk_id, Text = x.vmk_name });
            //model.selectVehicleMake = new SelectList(vm.getVehicleMakeList(), "vmk_id", "vmk_name");

            model.selectVehicleModel = new SelectList(vm.getVehicleModelList(""), "vg_id", "vg_name");

            model.Title = "Title goes here";

            return View(model);
        }

        VehicleModels vm = new VehicleModels();

        [HttpPost]
        public ActionResult Makes()
        {
            var makes = vm.getVehicleMakeList();

            return Json(new SelectList(makes, "vmk_id", "vmk_name"));
        }

        [HttpPost]
        public ActionResult Models(string vmk_id)
        {
            var models = vm.getVehicleModelList(vmk_id);

            return Json(new SelectList(models, "vg_id", "vg_Name"));
        }

    }
}

查看:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@Model.Title    </title>

   <script src="~/Scripts/jquery-1.7.1.min.js"></script>

    <script type="text/javascript">
        function getModels(vmk_id) {

            $.ajax({
                url: "@Url.Action("Models")",
                data: { vmk_id: vmk_id },
            dataType: "json",
            type: "POST",
            error: function () {
                alert("An error occurred.");
                errorHandler("error1");
            },
            success: function (data) {
                var items = "";
                $.each(data, function (i, item) {
                    items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
                });

                $("#selectVehicleModel").html(items);
            }
        });
    }

    $(document).ready(function () {
        $("#selectVehicleMake").change(function () {
            getModels($("#selectVehicleMake").val());
        });
    });


</script>

</head>
<body>
    <div>

@model BLPrototype.Models.vmCatalogue1
@using (Html.BeginForm())
{        
    <div class="editor-label">
        @Html.LabelFor(m => m.selectVehicleMake)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.selectVehicleMake, Model.selectVehicleMake, "Please select")

    </div>

    <div class="editor-label">
        @Html.LabelFor(m => m.selectVehicleModel)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(m => m.selectVehicleModel,  Model.selectVehicleModel, new { style = "width: 150px" })
    </div>    

}
</body>
</html>

以上示例显示了级联下拉列表。我已经看到了很多不同的填充下拉列表的方法,我想通过View-Model来实现。我真的不确定哪种方式最好。一些示例似乎只显示一个列表,一些列表包含selectlistitems,另一些只是一个选择列表。有人可以告诉我不同​​之处是什么是“更好”的方式......我知道它通常取决于应用程序。

我还希望能够预先选择Make,如果我愿意的话,我已经看到了一些以各种方式包含ID的示例,以及其他通过将其标记到选择列表末尾的示例。他们似乎都没有工作。

除非选择了make,否则模型不应该真正显示。我会通过CSS或其他方法来做到这一点吗?

最后我在make的末尾放了“Please Select”,所以它显示出来。这似乎不是一个很好的方法。你能指点我正确的方向吗?

感谢您的时间,我很抱歉这么多愚蠢的noobish问题!

由于

2 个答案:

答案 0 :(得分:1)

SelectListItems列表更明确,并为您提供Selected属性,但它更适合多选列表,如果您的视图在其他地方需要,您将无法再访问原始列表。

看看SelectList。在某些情况下,它可能对您更有效。你可以得到一个这样的:

myList.ToSelectList("ID", "Description")

new SelectList(myList, "ID", "Description)

添加:

data-placeholder="Please Select"

在包含“style = ...”的同一对象中,如果你想要一个占位符,直到选择了一个选项。

答案 1 :(得分:0)

我终于找到了我追求的解决方案。我会在这里发布,以防将来发现此帖有类似错误。

型号:

public class VehicleModels
{
    public List<vehicle_make> getVehicleMakeList()
    {
        using (var db = new BLEntities())
        {
            List<vehicle_make> vmk = db.vehicle_make.OrderBy(r => r.vmk_name).ToList();
            return vmk;
        }
    }

    public List<vehicle_group> getVehicleModelList(string vmk_id)
    {
        using (var db = new BLEntities())
        {
            List<vehicle_group> vmo = db.vehicle_group.Where(v => v.vg_vmk_id == vmk_id).OrderBy(r => r.vg_name).ToList();

            return vmo;
        }
    }

}

public class vmCatalogue3
{
    public string Title { get; set; }

    public string selectedMakeId { get; set; }
    public string SelectTopLine { get; set; }

    [Display(Name = "Select a make")]
    public SelectList selectVehicleMake { get; set; }

    [Display(Name = "Select a model")]
    public SelectList selectVehicleModel { get; set; }

}

控制器:

        public ActionResult Index()
    {
        VehicleModels vm = new VehicleModels();
        var model = new vmCatalogue3();

        model.selectedMakeId = "870";
        model.SelectTopLine = "Please Select";

        model.selectVehicleMake = new SelectList(vm.getVehicleMakeList(), "vmk_id", "vmk_name");
        model.selectVehicleModel = new SelectList(vm.getVehicleModelList(""), "vg_id", "vg_name");

        return View(model);            
    }

查看:

        @Html.DropDownListFor(m => m.selectedMakeId, Model.selectVehicleMake, Model.SelectTopLine )

希望能帮助别人!