开发者

ASP.NET MVC2 and EF4 - Creating checked checkboxes in an Edit view

I'm currently in the process of creating a shared Edit/Create view for my game review project and have hit a snag. Each game can be a title on a variety of platforms. I have this mapped as a many-to-many relationship in my EF4 model. For my view, I'd like to have开发者_Go百科 a series of checkboxes with the names of each platform, and, for the Edit view, have the correct boxes checked.

I can create the checkboxes easily with an HTML helper. My biggest problem is figuring out how to tell the helper to turn on isChecked on the correct platform values. Here's what I have so far:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<HandiGamer.ViewModels.AdminGameReviewViewModel>" %>

<p>
    <%: Html.LabelFor(model => model.GameData.GameTitle) %>
    <%: Html.TextBoxFor(model => model.GameData.GameTitle) %>
    <%: Html.ValidationMessageFor(model => model.GameData.GameTitle) %>
</p>
<p>
    <%: Html.LabelFor(model => model.Genres) %>
    <%: Html.DropDownList("Genre", new SelectList(ViewData["Genres"] as IEnumerable, "GenreID", "Name", Model.GameData.GenreID) %>
</p>
<p>
    <%: Html.LabelFor(model => model.Platforms) %>
    <% foreach(var item in Model.Platforms) { %>
        <%: Html.CheckBox(item.Name) %>
    <% } %>
</p>

And, my view model is:

public class AdminGameReviewViewModel
{
    public Game GameData { get; set; }
    public List<Genre> Genres { get; set; }
    public List<Platform> Platforms { get; set; }
}

Populated by:

    public ActionResult EditReview(int id)
    {
        var game = _siteDB.Games.Include("Genre").Include("Platforms").Include("Content").Single(g => g.GameID == id);
        var genres = _siteDB.Genres.ToList();
        var platforms = _siteDB.Platforms.ToList();
        var model = new { GameData = game, Genres = genres, Platforms = platforms }; 

        return View(model);
    }

So, I really just need a nudge in the right direction with the logic to determine which boxes should be checked.

Thanks.


Try using Html.CheckBoxFor

The predicate is an expression bound to the field (which should be a boolean).

<%: Html.CheckBoxFor(item => item.Name) %>

Also, i noticed in your Controller you are returning an anonymous type - that should be strongly-typed to your AdminGameReviewViewModel view-model, otherwise the model binding will not work.

e.g:

var model = new AdminGameReviewViewModel { GameData = game, Genres = genres, Platforms = platforms }; 

I'm not really sure what model property you want you want for the checkbox. Are you sure an item can/can't have a Name? It sounds like item.Name is a string, which is not valid for a checkbox - you should be binding to a boolean flag.

Maybe you should add another property to your ViewModel?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜