有没有办法从asp.net MVC中另一个下拉列表中的先前选择更改@ Html.DropDownList的值

时间:2017-04-18 02:04:09

标签: c# asp.net-mvc razor

我有一个问题,我想更改@ Html.DropDownList的值,它将更改以下@ Html.DropDownList中的值。

这是我的逻辑:我有2个列表

@{ 
     List<SelectListItem> CarMake = new List<SelectListItem>();
     CarMake.Add(new SelectListItem {Text="Acura", Value ="Acura" });
     CarMake.Add(new SelectListItem { Text = "Honda", Value = "Honda" });

     List<SelectListItem> CarModel = new List<SelectListItem>();
     CarModel.Add(new SelectListItem { Text = "Civic", Value = "Civic" });
     CarModel.Add(new SelectListItem { Text = "RL", Value = "RL" });
}

这是我的观点:

<div class="form-group">
    <label>Car name</label>
    @Html.DropDownList("Car make" ,CarMake, "Select", new { @class = "form-control" })
</div>
<div class="form-group">
    <label>Car model</label>
    @Html.DropDownList("Car make", CarModel, "Select", new { @class = "form-control" })
</div>

所以我想做的是如果 CarMake &#34; Acura&#34;然后只选择 CarModel &#34; RL&#34;将显示在第二个dropDownList中。这在webforms中更容易做,因为有一个selectedindexchanged。在MVC中有一种简单优雅的方法吗?

1 个答案:

答案 0 :(得分:0)

感谢所有评论员真正帮助过,但我要回答我的问题。

我所做的是创建一个名为CarMake的类,它必须在下面显示的类中显示类别和产品以及一些属性。

namespace hiophop.Models
{
    public class CarMake
    {
        public class Category
        {
            public int CategoryID { get; set; }
            public string CategoryName { get; set; }

        }

        public class Product
        {
            public int ProductID { get; set; }
            public string ProductName { get; set; }
            public int CategoryID { get; set; }
        }
    }
}

然后在我的控制器中我填充了列表,并使用两个值中的CategoryID属性制作我使它们彼此相等lstCat.CategoryID == lstprod.CategoryID在他们需要的类别1的字段中是丰田,因此丰田模型。我使用JsonRequestBehavior和linq来帮助我将所需数据传递给视图。

public class CarController : Controller
{
    List<Category> lstCat = new List<Category>()
    {
        new Category() { CategoryID = 1, CategoryName = "Toyota" },
        new Category() { CategoryID = 2, CategoryName = "Honda" },
        new Category() { CategoryID = 3, CategoryName = "Chevy" }
    };

    List<Product> lstProd = new List<Product>()
    {
        new Product() { ProductID = 1, ProductName = "camry", CategoryID = 1 },
        new Product() { ProductID = 2, ProductName = "rav4", CategoryID = 1 },
        new Product() { ProductID = 3, ProductName = "accord", CategoryID = 1 },
        new Product() { ProductID = 4, ProductName = "civic", CategoryID = 2 },
        new Product() { ProductID = 5, ProductName = "fit", CategoryID = 2 },
        new Product() { ProductID = 6, ProductName = "vue", CategoryID = 2 },
        new Product() { ProductID = 7, ProductName = "malibu", CategoryID = 3 },
        new Product() { ProductID = 8, ProductName = "impala", CategoryID = 3 },
        new Product() { ProductID = 9, ProductName = "iroc", CategoryID = 3 }
    };

    public ActionResult GetCategories()
    {
        return Json(lstCat, JsonRequestBehavior.AllowGet);

    }

    public ActionResult GetProducts(int intCatID)
    {
        var products = lstProd.Where(p => p.CategoryID == intCatID);
        return Json(products, JsonRequestBehavior.AllowGet);

    }
    [HttpGet]
    public ActionResult Index()
    {

        return View();
    }

    [HttpPost]
    public ActionResult Index(string category ,string product)
    {


        ViewBag.x ="Product"+ product;
        ViewBag.y = "catego" + category;
        return View();
    }
}

然后在我看来我写了这个并且它有用了

 @ViewBag.y
@ViewBag.x


@using (Html.BeginForm("Index", "Car", FormMethod.Post))
{
    <div>
        <label for="category">Category</label>
        <select id="category" name="c" class="form-control"></select>
        <label for="product">Product</label>
        <select id="product" name="p"  class="form-control"></select>



        <input type="submit" id="Button" class="btn btn-default" />




    </div>
}
@section scripts {
    <script type="text/javascript">
        $(document).ready(function () {
            // Get a list of categories and a list of products of the first category.
            $.getJSON('/Car/GetCategories', null, function (data) {
                $.each(data, function () {
                    $('#category').append('<option value=' +
                      this.CategoryID + '>' + this.CategoryName + '</option>');
                });
                $.getJSON('/Car/GetProducts', { intCatID: $('#category').val() }, function (data) {
                    $.each(data, function () {
                        $('#product').append('<option value=' +
                          this.ProductID + '>' + this.ProductName + '</option>');

                    });
                }).fail(function (jqXHR, textStatus, errorThrown) {
                    alert('Error getting products!');
                });
            }).fail(function (jqXHR, textStatus, errorThrown) {
                alert('Error getting categories!');
            });

            // Dropdown list change event.
            $('#category').change(function () {
                $('#product option').remove();
                $.getJSON('/Car/GetProducts', { intCatID: $('#category').val() }, function (data) {
                    $.each(data, function () {
                        $('#product').append('<option value=' +
                          this.ProductID + '>' + this.ProductName + '</option>');
                    });
                }).fail(function (jqXHR, textStatus, errorThrown) {
                    alert('Error getting products!');
                });
            });
        });







        $(document).ready(function () {
            $("#Button1").click(function () {
                $.ajax({
                    type: 'POST',
                    contentType: "application/json;charset=utf-8",
                    url: '/Car/Index',
                    data: "{'Category':'" + document.getElementById('#category') + "','product':'" + document.getElementById('#product') + " '}",
                    async: false,
                    success: function (response) {
                        $('#category').val('');
                        $('#product').val('');

                        alert("record has been saved in database");

                    },
                    error: function () {
                        console.log('there is some error');
                    }

                });

            });

        });
    </script>
}

在我的控制器中,它获取post和return

的值
 [HttpPost]
    public ActionResult Index(string category ,string product)
    {


        ViewBag.x ="Product"+ product;
        ViewBag.y = "catego" + category;
        return View();
    }

这将检索上面控制器中CategoryID和ProductID的索引号值位置,并将其传递给viewbag。我正在努力研究如何传递文本值。