开发者

Working with a list of checkboxes in an ASP.Net MVC View

I have three tables in my database: Pages, Tags and Joiner

My entities look like this (abbreviated)...

public class Page
{        
    public int PageId { get; private set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public List<Tag> Tags { get; set; }
}

public class Tag
{        
    public int TagId { get; private set; }
    public string Name{ get; set; }
}

Each page can have any number of tags, and each tag can be applied to any number of pages, hence the Joiner table for the many-to-many relationship.

On the Edit view for the Pages controller, I want the user to be able to update the title and body, as well as select any of the tags from the tags table in the form of a list of checkboxes.

For example, if ten tags exist in the tags table and the current page has two tags in Page.Tags, then ten checkboxes will be displayed with two of them ticked. The user can then change the 开发者_运维技巧selection and save the page, and the joiner table will get updated.

What is the best way to do this? I am happy with the database update code, it's the View code that I'm not sure about.


You can try something like that:

First, define a viewmodel like this:

public class PageViewModel
{
    public Page pageToEdit{get;set;}
    public IEnumerable<Tag> Tags {get;set;}
}

Then, in your controller

public ActionResult Edit(int id)
{
    PageViewModel model = new PageViewModel();
    model.Tags = yourRepository.SelectTags();
    model.PageToEdit =  yourRepository.SelectPage(id); 
    return this.View(model);
}

in your View inherits ViewPage<PageViewModel> and the content must looke like this:

<% using(Html.BeginForm()){ %>

[...] 
<%
foreach(Tag tag in Model.Tags)
{
      Response.Write(Html.CheckBox("tagId_"+tag.TagId,Model.PageToEdit.Tags.Select(t=>t.TagId).Contains(tag.Tagid));
}
%>
[...]
<% } %>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜