Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
397 views
in Technique[技术] by (71.8m points)

checkboxlist in asp.net MVC

I want to create a checkboxlist in asp.net mvc view and want to display week days (monday tuesday, ....). I want to save the value(s) selected by user in database. How can I do this in MVC2

Someone suggested me to use "Enumeration Types as Bit Flags" mentioned here:

http://msdn.microsoft.com/en-us/library/cc138362.aspx

how can I use it ?

Please suggest solution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes i would also suggest an enum in this scenario.

Here is how you can do it in ASP.NET MVC:

Your enum should look like this (see the link you provided):

[Flags]
public enum Days 
{
    Sunday = 0x1,
    Monday = 0x2,
    Tuesday = 0x4,
    Wednesday = 0x8,
    Thursday = 0x10,
    Friday = 0x20,
    Saturday = 0x40 
}

For reusability purposes I have created an generic html helper that looks like this:

public static IHtmlString CheckboxListForEnum<T>(this HtmlHelper html, string name, T modelItems) where T : struct
{
    StringBuilder sb = new StringBuilder();

    foreach (T item in Enum.GetValues(typeof(T)).Cast<T>())
    {
        TagBuilder builder = new TagBuilder("input");
        long targetValue = Convert.ToInt64(item);
        long flagValue = Convert.ToInt64(modelItems);

        if ((targetValue & flagValue) == targetValue)
            builder.MergeAttribute("checked", "checked");

        builder.MergeAttribute("type", "checkbox");
        builder.MergeAttribute("value", item.ToString());
        builder.MergeAttribute("name", name);
        builder.InnerHtml = item.ToString();

        sb.Append(builder.ToString(TagRenderMode.Normal));
    }

    return new HtmlString(sb.ToString());
}

You can use the same html helper for all enumeration types.

Usage:


Now for demonstration purposes let say that you have a model like this:

Model:

public class TVShow
{
    public string Title { get; set; }

    public string Description { get; set; }

    public Days AvailableOn { get; set; }

}

Controller Action:

public ActionResult Show()
{
    var show = new TVShow
    {
        Title = "Late Late Show",
        AvailableOn = Days.Monday | Days.Friday
    };
    return View(show);
}

View (strongly typed):

<%: Model.Title %>

<%: Model.Description %>

<%: Html.CheckboxListForEnum<Days>("days", Model.AvailableOn)%>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...