我目前正在通过MvcMusicStore教程第二次作为个人项目。这次代替实体框架我试图使用nHibernate以及使用Castle Windsor的一些IoC。
我遇到的第一个障碍与嵌套类和模型绑定有关。我能够显示专辑列表然后编辑它们。只要我编辑Title,Price或AlbumArtUrl字段,我也能够持久更改数据库。当我尝试编辑Artist或Genre字段时,会发生以下错误。
“无法更新'MvcMusicStore.Models.Album'类型的模型。”
在对UpdateModel的调用中发生此错误,所以我假设它与绑定有关但我完全难以理解如何继续。从我在StackOverflow和其他地方所做的搜索来看,这似乎是一个常见问题,但到目前为止我还没有找到解决方案。
我希望有人能够发现我在这里做错了什么并提出解决方案。
相册
public class Album
{
public virtual int AlbumId { get; set; }
public virtual Artist Artist { get; set; }
public virtual Genre Genre { get; set; }
public virtual string Title { get; set; }
public virtual decimal Price { get; set; }
public virtual string AlbumArtUrl { get; set; }
}
StoreManagerViewModel
public class StoreManagerViewModel
{
public Album Album { get; set; }
public IList<Artist> Artists { get; set; }
public IList<Genre> Genres { get; set; }
}
Edit.aspx
<%@ Page Language="C#" MasterPageFile="/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<MvcMusicStore.ViewModels.StoreManagerViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Edit - <%: Model.Album.Title %>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Edit Album</h2>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Edit Album</legend>
<%: Html.EditorFor(model => model.Album,
new { Artists = Model.Artists, Genres = Model.Genres}) %>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
Album.ascx
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcMusicStore.Models.Album>" %>
<div class="editor-label">
<%: Html.LabelFor(model => model.Title) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Title) %>
<%: Html.ValidationMessageFor(model => model.Title) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Price) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Price, String.Format("{0:F}", Model.Price)) %>
<%: Html.ValidationMessageFor(model => model.Price) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.AlbumArtUrl) %>
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.AlbumArtUrl) %>
<%: Html.ValidationMessageFor(model => model.AlbumArtUrl) %>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Artist)%>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.Artist, new SelectList(ViewData["Artists"] as IEnumerable, "ArtistId", "Name", Model.Artist))%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Genre)%>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.Genre, new SelectList(ViewData["Genres"] as IEnumerable, "GenreId", "Name", Model.Genre))%>
</div>
StoreManagerController
public ActionResult Edit(int id)
{
var viewModel = new StoreManagerViewModel
{
Album = AlbumRepository.GetById(id),
Genres = GenreRepository.GetAll().ToList(),
Artists = ArtistRepository.GetAll().ToList(),
};
return View(viewModel);
}
[HttpPost, UnitOfWork]
public ActionResult Edit(int id, FormCollection formValues)
{
var album = AlbumRepository.GetById(id);
try
{
UpdateModel(album, "Album");
AlbumRepository.SaveOrUpdate(album);
return RedirectToAction("Index");
}
catch
{
var viewModel = new StoreManagerViewModel
{
Album = album,
Genres = GenreRepository.GetAll().ToList(),
Artists = ArtistRepository.GetAll().ToList(),
};
return View(viewModel);
}
}
更新1:
如果我在UpdateModel断点并查看ValueProvider.GetValue(“Album.Artist”),我可以看到更新的ArtistId。这告诉我,我完全误解了这应该如何运作。
我真的应该让UpdateModel处理它所喜欢的属性:
UpdateModel(album, "Album", new string[] { "Title", "Price", "AlbumArtUrl" });
然后根据ValueProvider中的ArtistId,GenreId自己提取对象,手动更新Artist和Genre属性?
更新2
修复了什么?
Album.ascx
<div class="editor-label">
<%: Html.LabelFor(model => model.Artist)%>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.Artist, new SelectList(ViewData["Artists"] as IEnumerable, "ArtistId", "Name", Model.Artist.ArtistId))%>
</div>
<div class="editor-label">
<%: Html.LabelFor(model => model.Genre)%>
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.Genre, new SelectList(ViewData["Genres"] as IEnumerable, "GenreId", "Name", Model.Genre.GenreId))%>
</div>
StoreManagerController
UpdateModel(album, "Album", new string[] { "Title", "Price", "AlbumArtUrl" });
album.Artist = ArtistRepository.GetById(Int32.Parse(formValues["Album.Artist"]));
album.Genre = GenreRepository.GetById(Int32.Parse(formValues["Album.Genre"]));
AlbumRepository.SaveOrUpdate(album);
这是有效的,我不知道它是如何做这种事情的。如果不是,那么会有人把我弄好吗?
答案 0 :(得分:0)
您必须在UpdateModel()
此外,如果您有强类型视图,则可以将模型用作控制器参数,而不是FormCollection。另外,最好排除已编辑相册的ID。
ActionResult Edit([Bind(Exclude = "AlbumId")]Album album)
你将从你的表单中获取相册的所有字段进行编辑。
关于您的代码:
现在我在你的代码中看到你在你的db
var album = AlbumRepository.GetById(id);
然后尝试用它做一些操作,并且不清楚如何从视图中绑定信息。
答案 1 :(得分:0)
为了解决这个问题,我在ViewModel中创建了一个链接到相关对象的属性,然后对该属性进行了绑定:
public class User
{
[Required(ErrorMessage = "Your first name is required.")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Your last name is required.")]
public string LastName { get; set; }
[Required(ErrorMessage = "A logon name is required.")]
public string Logon { get; set; }
[Required(ErrorMessage = "A password is required.")]
public string Password { get; set; }
[Required(ErrorMessage = "A role is required.")]
public string Role { get; set; }
[Required(ErrorMessage = "An airport is required.")]
public Airport Airport { get; set; }
[DisplayName("Is Active")]
bool IsActive { get; set; }
}
<div class="form-field">
<div class="field-label"><%= Html.LabelFor(m => m.User.Airport) %>:</div>
<div class="field-input"><%= Html.DropDownListFor(m => m.UserAirportId, new SelectList(Model.Airports, "Id", "Name"))%></div>
<div class="field-result"><%= Html.ValidationMessageFor(m => m.User.Airport) %></div>
</div>
public class UserViewModel
{
public User User { get; set; }
public List<Airport> Airports { get; set; }
public List<String> Roles { get; set; }
//Hack to get around non-binding of complex objects by UpdateModel
public Guid UserAirportId
{
get
{
if (User != null && User.Airport != null)
return User.Airport.Id;
return Guid.Empty;
}
set
{
if (User == null)
return;
var airport = Airports.Where(m => m.Id == value).FirstOrDefault();
if (airport == null)
return;
User.Airport = airport;
}
}
}