我距离让我的创建表单工作一英寸。我的问题是传递到视图模型中的表单的一些数据不会在回发中发回。
型号:
Game:
GameID - int (primary key, auto-incr)
GameTitle - nvarchar(100)
ReviewText - text
ReviewScore - smallint
Pros - text
Cons - text
LastModified - Datetime
GenreID - int (foreign key from Genres)
Platform:
PlatformID - int (primary key, auto-incr)
Name - nvarchar(50)
GamePlatform (not visible as an EF 4 entity):
GameID - int (foreign key from Games)
PlatformID - int (foreign key from Platforms)
我正在使用的视图模型:
public class PlatformListing
{
public Platform Platform { get; set; }
public bool IsSelected { get; set; }
}
public class AdminGameReviewViewModel
{
public Game GameData { get; set; }
public List<Genre> AllGenres { get; set; }
public List<PlatformListing> AllPlatforms { get; set; }
}
表格本身:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<HandiGamer.WebUI.ViewModels.AdminGameReviewViewModel>" %>
<p>
<%: Html.Label("Game Title") %>
<%: Html.TextBoxFor(model => Model.GameData.GameTitle) %>
<%: Html.ValidationMessageFor(model => Model.GameData.GameTitle) %>
</p>
<p>
<%: Html.LabelFor(model => Model.GameData.GenreID) %>
<%: Html.DropDownListFor(m => Model.GameData.GenreID, new SelectList(Model.AllGenres, "GenreID", "Name", Model.GameData.GenreID)) %>
</p>
<p>
<%: Html.Label("Platforms") %><br />
<% for(var i = 0; i < Model.AllPlatforms.Count; ++i)
{ %>
<%: Model.AllPlatforms[i].Platform.Name %> <%: Html.CheckBoxFor(p => Model.AllPlatforms[i].IsSelected) %>
<% } %>
</p>
<p>
<%: Html.Label("Review") %>
<%: Html.TextAreaFor(model => Model.GameData.ReviewText) %>
</p>
<p>
<%: Html.Label("Review Score") %>
<%: Html.DropDownListFor(m => Model.GameData.ReviewScore, new SelectList(new int[] {1, 2, 3, 4, 5}))%>
</p>
<p>
<%: Html.LabelFor(model => model.GameData.Pros) %><br />
<%: Html.TextAreaFor(model => model.GameData.Pros) %>
</p>
<p>
<%: Html.LabelFor(model => model.GameData.Cons) %><br />
<%: Html.TextAreaFor(model => model.GameData.Cons) %>
</p>
最后,我的Create方法(我试图让它工作的准系统):
[HttpPost]
public ActionResult CreateReview([Bind(Prefix = "GameData")]Game newGame, [Bind(Prefix = "AllPlatforms")]List<PlatformListing> PlatformList)
{
try
{
foreach(var plat in PlatformList)
{
if (plat.IsSelected == true)
{
newGame.Platforms.Add(plat.Platform);
}
}
newGame.LastModified = DateTime.Now;
_siteDB.Games.AddObject(newGame);
_siteDB.SaveChanges();
// add form data to entities, then save
return RedirectToAction("Index");
}
catch
{
return View();
}
}
问题当然是我的复选框。布尔值isSelected设置正常,但是在发布数据时,缺少相应的Platform对象。我以为他们会自动被传回去。那么,关于如何传回PlatformListing的实际Platform部分的任何建议?