0

我想在MvcMusicStore示例中使用流利NHibernate而不是實體框架,並且在使用Create創建新相冊時出現填充ArtistId和GenreId的問題視圖。我覺得這件事情做的其實我正在參照其他物體在MVC中使用流利NHibernate映射創建視圖中的對象

相冊地圖爲:

public class AlbumMap:ClassMap<Album> 
    { 
     public AlbumMap() 
     { 
      Id(x => x.AlbumId); 
      Map(x => x.AlbumArtUrl); 
      References(x => x.Artist).Cascade.All().Column("ArtistId"); 
      References(x => x.Genre).Cascade.All().Column("GenreId"); 
      Map(x => x.Price); 
      Map(x => x.Title); 
     } 
    } 

控制器中創建方法是這樣的:

public ActionResult Create() 
    { 
     MusicRepository repository = new MusicRepository(); 
     ViewBag.ArtistId = new SelectList(repository.GetArtists(), "ArtistId", "Name"); 
     ViewBag.GenreId = new SelectList(repository.GetGenres(), "GenreId", "Name"); 
     return View(); 
    } 

和創建視圖中出現問題的部分是:

<div class="editor-label"> 
     @Html.LabelFor(model => model.Genre, "Genre") 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownList("GenreId", String.Empty) 
     @Html.ValidationMessageFor(model => model.Genre) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Artist, "Artist") 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownList("ArtistId", String.Empty) 
     @Html.ValidationMessageFor(model => model.Artist) 
    </div> 

在數據庫中創建新的「專輯」後,其他字段(例如Title和AlbumUrl)被填入,但ArtistId和GenreId被設置爲空。

回答

0

你可能可以告訴我這個很新,但是我已經解決了我的問題。我不希望這首先改變下拉列表傭工dropdownlistfor使其能夠救回來:

<div class="editor-label"> 
     @Html.LabelFor(model => model.Genre, "Genre") 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownListFor(model => model.Genre.GenreId, (SelectList)ViewBag.GenreId,"Please select") 
     @Html.ValidationMessageFor(model => model.Genre.GenreId) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.Artist, "Artist") 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownListFor(model => model.Artist.ArtistId, (SelectList)ViewBag.ArtistId,"Please select") 
     @Html.ValidationMessageFor(model => model.Artist.ArtistId) 
    </div> 

這回我初始化的藝術家和流派性質的專輯。唯一的是他們只包含Id屬性,所以我必須在保存之前使用它們來獲取剩餘的屬性(使用nhibernate):

[HttpPost] 
    public ActionResult Create(Album album) 
    { 
     try 
     { 
      MusicRepository repository = new MusicRepository(); 
      if (ModelState.IsValid) 
      { 
       album.Artist = repository.GetArtistById(album.Artist.ArtistId); 
       album.Genre = repository.GetGenreById(album.Genre.GenreId); 
       repository.AddAlbum(album); 
       return RedirectToAction("Index"); 
      } 
      ViewBag.ArtistId = new SelectList(repository.GetArtists(), "ArtistId", "Name"); 
      ViewBag.GenreId = new SelectList(repository.GetGenres(), "GenreId", "Name"); 
      return View(album); 
     }