MVC下拉列表,包含数据库中的值

时间:2014-05-09 23:48:03

标签: asp.net-mvc entity-framework database-relations

基于https://mvcmusicstore.codeplex.com/尝试在购买之前获取详细信息相册中的属性下拉列表。我创建了一个表,其中包含属性和具有属性的表的映射。原则上,产品必须参考属性图,即定义akrybuty将在下拉列表中显示的内容。在这里输入图像描述有人可以帮我在应用程序中实现吗?

我知道在视图中添加

@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

namespace MvcMusicStore.Models
{
    [Bind(Exclude = "AlbumId")]
    public class Album
    {
        [ScaffoldColumn(false)]
        public int AlbumId { get; set; }

        [DisplayName("Genre")]
        public int GenreId { get; set; }

        [DisplayName("Artist")]
        public int ArtistId { get; set; }

        [Required(ErrorMessage = "An Album Title is required")]
        [StringLength(160)]
        public string Title { get; set; }

        [Required(ErrorMessage = "Price is required")]
        [Range(0.01, 100.00,
            ErrorMessage = "Price must be between 0.01 and 100.00")]
        public decimal Price { get; set; }

        [DisplayName("Album Art URL")]
        [StringLength(1024)]
        public string AlbumArtUrl { get; set; }

        public virtual Genre Genre { get; set; }
        public virtual Artist Artist { get; set; }
        public virtual List<OrderDetail> OrderDetails { get; set; }
    }
}

2

namespace MvcMusicStore.Models
{
    public class Artist
    {
        public int ArtistId { get; set; }
        public string Name { get; set; }
    }
}

3

namespace MvcMusicStore.Models
{
    public partial class Genre
    {
        public int GenreId { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public List<Album> Albums { get; set; }
    }
}

查看:

@model MvcMusicStore.Models.Album

@{
ViewBag.Title = "Album - " + Model.Title;
}

<h2>@Model.Title</h2>

<p>
<img alt="@Model.Title" src="@Model.AlbumArtUrl" />
</p>

 <div id="album-details">
<p>
    <em>Genre:</em>
    @Model.Genre.Name
</p>
<p>
    <em>Artist:</em>
    @Model.Artist.Name
</p>
<p>
    <em>Price:</em>
    @String.Format("{0:F}", Model.Price)
</p>
<p class="button">
    @Html.ActionLink("Add to cart", "AddToCart", 
    "ShoppingCart", new { id = Model.AlbumId }, "")
</p>
</div>

我目前的代码。

我想添加dropdownlisty,因为每个产品都有不同的属性,例如一个将有8种类型的封面,而另一个只有两种。当您选择下面的每个项目(每个项目有8个封面)下拉列表时,它将zmianiała其内容

想象一下他想要实现的目标。

https://i.stack.imgur.com/IIApj.png

1 个答案:

答案 0 :(得分:0)

假设您希望每次在第一个下拉列表中选择不同的值时更新第二个下拉列表的值,一种方法是通过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代码)

控制器操作:

    [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>