Asp.net mvc MVC dropdownlist,包含数据库中的值

Asp.net mvc MVC dropdownlist,包含数据库中的值,asp.net-mvc,entity-framework,database-relations,Asp.net Mvc,Entity Framework,Database Relations,基于在购买前尝试获取详细信息相册中属性的下拉列表。我创建了一个带有属性映射的表和一个带有属性的表。原则上,产品必须参考属性映射,该映射用于定义Akrybuto将出现在下拉列表中的内容。在此处输入图像描述有人可以帮助我在应用程序中实现吗 我知道在视图中只需添加 @Html.DropDownList("Name",new SelectList(ViewBag.Names)) ,我不知道如何从属性映射中获取数据,以便每个相册都有自己的属性集 控制器: namespace MvcMusicStore.

基于在购买前尝试获取详细信息相册中属性的下拉列表。我创建了一个带有属性映射的表和一个带有属性的表。原则上,产品必须参考属性映射,该映射用于定义Akrybuto将出现在下拉列表中的内容。在此处输入图像描述有人可以帮助我在应用程序中实现吗

我知道在视图中只需添加

@Html.DropDownList("Name",new SelectList(ViewBag.Names))
,我不知道如何从属性映射中获取数据,以便每个相册都有自己的属性集

控制器:

namespace MvcMusicStore.Controllers
{
    public class StoreController : Controller
    {
        MusicStoreEntities storeDB = new MusicStoreEntities();

        //
        // GET: /Store/

        public ActionResult Index()
        {
            var genres = storeDB.Genres.ToList();

            return View(genres);
        }


        public ActionResult Browse(string genre)
        {
            // Retrieve Genre and its Associated Albums from database
            var genreModel = storeDB.Genres.Include("Albums")
                .Single(g => g.Name == genre);

            return View(genreModel);
        }


        public ActionResult Details(int id)
        {
            var album = storeDB.Albums.Find(id);

            return View(album);
        }        
    }
}
型号:

1. 3.
名称空间MvcMusicStore.Models
{
公共部分类体裁
{
public int GenreId{get;set;}
公共字符串名称{get;set;}
公共字符串说明{get;set;}

public List

假设您希望在第一个下拉列表中每次选择不同的值时更新第二个下拉列表的值,一种方法是通过jQuery、JSON、视图模型和一些控制器操作(注意,这并没有实现最佳实践,比如在控制器操作中不进行数据库调用,从视图中提取JS并将其放入模块中):

实体:

namespace DataModel
{
    public class Item
    {
        [Id]
        public int ItemId {get; set;}

        public string ItemText {get; set;} 
    }

    public class Attribute
    {
        [Id]
        public int AttributeId {get; set;}

        public string AttributeText {get; set;}
    }
}
(省略
DbContext
code)

控制器操作:

    [HttpGet]
    public ActionResult TestDropdown()
    {
        using(var context = new YourDbContext()) // it's good practice to use the using() statement to dispose of the DbContext's resources right when it's finished, rather than setting a class-level variable
        {
            var model = new Models.TestDropdownViewModel();
            // gets all the items; you might want to filter for items that you want to display 
            model.Items = context.Items.ToList().Select(i => new SelectListItem()
                {
                     Text = i.ItemText,
                     Value = i.ItemId.ToString() // this is probably an ID of the row for the corresponding Item
                });

            model.Attributes = context.Attributes.First().Select(a => new SelectListItem
                {
                    Text = a.AttributeText,
                    Value = a.AttributeId.ToString()
                });

            return View(model);
        }
    }

    [HttpGet]
    public JsonResult GetAttributesForItem(int selectedId)
    {
        using(var context = new YourDbContext())
        {
            var attributes = context.Attributes.Where(a => a.Item.ItemId == selectedId).ToList();

            return Json(addresses.Select(a => new { Value = a.AddressId.ToString(), Text = a.Address1 }), JsonRequestBehavior.AllowGet);
        }
    }
视图模型:

using System.Web.Mvc;
using System.Collections.Generic;

namespace Models
{
    public class TestDropdownViewModel
    {
        public IEnumerable<SelectListItem> Items { get; set; }

        public IEnumerable<SelectListItem> Attributes { get; set; }
    }
}
使用System.Web.Mvc;
使用System.Collections.Generic;
名称空间模型
{
公共类TestDropdownViewModel
{
公共IEnumerable项{get;set;}
公共IEnumerable属性{get;set;}
}
}
局部视图:

// make sure jQuery is loaded in your _Layout.cshtml if you're using that pattern

@model Models.TestDropdownViewModel

@{
    ViewBag.Title = "TestDropdown";
}

<div>
    @Html.DropDownList("Items", Model.Items, new { id = "Items" })
</div>
<br />
<div>
    @Html.DropDownList("Attributes", Model.Attributes, new { id = "Attributes" })
</div>

<script type="text/javascript">
    $(document).ready(function () {
        $('#Items').change(function () {
            var selectedId = this.value;
            $.getJSON('/GetAttributesForItem?', { id: selectedId }, function (data) {
                var attributes = $('#Attributes');
                var options;
                $.each(data, function (index, elem) {
                    options += "<option value='" + elem.Value + "'>" + elem.Text + "</option>";
                });
                attributes.html(options);
            });
        });
    });
</script>
//如果您正在使用该模式,请确保jQuery已加载到_Layout.cshtml中
@model Models.TestDropdownViewModel
@{
ViewBag.Title=“TestDropdown”;
}
@Html.DropDownList(“Items”,Model.Items,new{id=“Items”})

@DropDownList(“Attributes”,Model.Attributes,new{id=“Attributes”}) $(文档).ready(函数(){ $('#Items')。更改(函数(){ var selectedId=this.value; $.getJSON('/GetAttributesForItem?',{id:selectedId},函数(数据){ 变量属性=$(“#属性”); var期权; $.each(数据、函数(索引、元素){ 选项+=“”+元素文本+“”; }); html(选项); }); }); });
你能阅读你的问题并尝试澄清吗?你的描述很难理解。你还需要添加更多的代码,至少是你分配给
ViewBag的代码。姓名
感谢你对我的主题感兴趣。我更新了你的帖子,并添加了他想要实现的目标的图片。
namespace DataModel
{
    public class Item
    {
        [Id]
        public int ItemId {get; set;}

        public string ItemText {get; set;} 
    }

    public class Attribute
    {
        [Id]
        public int AttributeId {get; set;}

        public string AttributeText {get; set;}
    }
}
    [HttpGet]
    public ActionResult TestDropdown()
    {
        using(var context = new YourDbContext()) // it's good practice to use the using() statement to dispose of the DbContext's resources right when it's finished, rather than setting a class-level variable
        {
            var model = new Models.TestDropdownViewModel();
            // gets all the items; you might want to filter for items that you want to display 
            model.Items = context.Items.ToList().Select(i => new SelectListItem()
                {
                     Text = i.ItemText,
                     Value = i.ItemId.ToString() // this is probably an ID of the row for the corresponding Item
                });

            model.Attributes = context.Attributes.First().Select(a => new SelectListItem
                {
                    Text = a.AttributeText,
                    Value = a.AttributeId.ToString()
                });

            return View(model);
        }
    }

    [HttpGet]
    public JsonResult GetAttributesForItem(int selectedId)
    {
        using(var context = new YourDbContext())
        {
            var attributes = context.Attributes.Where(a => a.Item.ItemId == selectedId).ToList();

            return Json(addresses.Select(a => new { Value = a.AddressId.ToString(), Text = a.Address1 }), JsonRequestBehavior.AllowGet);
        }
    }
using System.Web.Mvc;
using System.Collections.Generic;

namespace Models
{
    public class TestDropdownViewModel
    {
        public IEnumerable<SelectListItem> Items { get; set; }

        public IEnumerable<SelectListItem> Attributes { get; set; }
    }
}
// make sure jQuery is loaded in your _Layout.cshtml if you're using that pattern

@model Models.TestDropdownViewModel

@{
    ViewBag.Title = "TestDropdown";
}

<div>
    @Html.DropDownList("Items", Model.Items, new { id = "Items" })
</div>
<br />
<div>
    @Html.DropDownList("Attributes", Model.Attributes, new { id = "Attributes" })
</div>

<script type="text/javascript">
    $(document).ready(function () {
        $('#Items').change(function () {
            var selectedId = this.value;
            $.getJSON('/GetAttributesForItem?', { id: selectedId }, function (data) {
                var attributes = $('#Attributes');
                var options;
                $.each(data, function (index, elem) {
                    options += "<option value='" + elem.Value + "'>" + elem.Text + "</option>";
                });
                attributes.html(options);
            });
        });
    });
</script>