ASP.NET MVC 4 List<T> to ICollection<T>
本文关键字:gt lt to ICollection List MVC NET ASP | 更新日期: 2023-09-27 18:33:09
我的项目涉及向事件添加艺术家集合。 目前,我在视图中有一个复选框表单中的艺术家列表,然后我有一个填充了从表单中选择的艺术家的列表。 我正处于一个棘手的问题,因为我需要将该列表放入事件中(请参阅此处注释所需的//代码)。 在此之后,我将在 Journal 类上执行类似的操作。
型
public class EventArtistModel
{
public int EventId { get; set; }
public string ArtistName { get; set; }
public string ArtistGenre { get; set; }
}
public class Event
{
public int Id { get; set; }
[DisplayName("Event Name")]
public string name { get; set; }
[DisplayName("Location")]
public string location { get; set; }
[DisplayName("Event Date")]
public string date { get; set; }
public virtual ICollection<Artist> Artists { get; set; }
}
public class Artist
{
public int Id { get; set; }
public string Name { get; set; }
public string Genre { get; set; }
public virtual ICollection<Event> Events { get; set; }
public virtual ICollection<Journal> Journals { get; set; }
}
控制器
public ActionResult AddArtistToEvent(int id = 0)
{
Event even = db.Events.Find(id);
List<Artist> artists = even.Artists.Cast<Artist>().ToList();
var model = db.Artists
.OrderBy(a => a.Name)
.Select(a => new EventArtistModel
{
EventId = id,
ArtistName = a.Name,
ArtistGenre = a.Genre
});
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddToEvent(Artist[] artistsSelected, int id = 0)
{
List<Artist> artistList = new List<Artist>();
foreach (Artist artist in artistsSelected)
{
artistList.Add(artist);
}
//code needed here
return RedirectToAction("Index");
}
视图
@model IEnumerable<EventJournal3.Models.EventArtistModel>
@{
ViewBag.Title = "Add an Artist To an Event";
}
@section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>@ViewBag.Title</h1>
</hgroup>
</div>
</section>
}
@foreach(var item in Model)
{
var id = item.EventId;
ViewBag.Message = id.ToString();
}
<form action="/Artist/AddToEvent/@ViewBag.Message" method="post">
<div class="container">
<div class="row">
<div class="col-xs-4">
<ul>
@foreach (var item in Model)
{
var id = item.EventId;
<li>
@Html.DisplayFor(modelItem => item.ArtistName)
~~ <input type="checkbox" name="selectedArtists" value="@item.ArtistName"/>
</li>
}
</ul>
</div>
<div class="col-xs-1">
@if (User.IsInRole("Admin"))
{
<input type="submit" value="Add" class="btn btn-info" />
}
| @Html.ActionLink("Back to List", "Index")
</div>
</div>
</div>
</form>
试试这个:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddToEvent(Artist[] artistsSelected, int id = 0)
{
Event _event = db.Events.Find(id);
foreach (Artist artist in artistsSelected)
{
_event.Artists.Add(artist);
}
return RedirectToAction("Index");
}