0

So I have this Model:

    public int ID { get; set; }
    [Required(ErrorMessage = "A Name is required")]
    public string Name { get; set; }
    public bool GreenCircle { get; set; }
    public bool BlueSquare { get; set; }
    public bool BlackDiamond { get; set; }
    public bool TerrainPark { get; set; }

Currently the View I have that allows a user to create a profile sets up Checkboxes for the bool properties listed here.

I am looking for a way to set up JQuery Validation that will require that one and only one of these bool properties is set to true so I'm thinking I should be using RadioButtons but I'm not quite sure how I can group those when they get set up in a View or how I can perform that type of validation.

Any ideas? I'm here to learn so please point me in the right direction for research if you must; thank you in advance.

2
  • Looks like an enum will more suit your needs. Commented Jan 21, 2013 at 7:51
  • Could you please elaborate? Commented Jan 21, 2013 at 7:52

1 Answer 1

1

Use an enum. For example:

public enum MyEnum
{
    GreenCircle,
    BlueSquare,
    BlackDiamond,
    TerrainPark
}

Then use it in your model instead of four different boolean properties.

public class MyModel
{
    public MyEnum MyOption { get; set; }
}

Then generate radiobuttons in your view.

@using (Html.BeginForm())
{
    @Html.RadioButtonFor(m => m.MyOption, (int)MyEnum.BlackDiamond);
    <span>Black Diamond</span><br />
    @Html.RadioButtonFor(m => m.MyOption, (int)MyEnum.BlueSquare, 
        new { @checked = "true" });
    <span>Blue Square</span><br />
    @Html.RadioButtonFor(m => m.MyOption, (int)MyEnum.GreenCircle);
    <span>Green Circle</span><br />
    @Html.RadioButtonFor(m => m.MyOption, (int)MyEnum.TerrainPark);
    <span>Terrain Park</span><br />
}

Remark: Maybe you can implement an HTML helper to generate the radio button markup for you.

Sign up to request clarification or add additional context in comments.

3 Comments

Awesomeness. I'm going to go give this a go, expect an update and thank you very much!
So despite the fact that my view is using a strongly typed model with the correct model referenced at the top I keep getting the error that: "ExperienceLevel does not exist in the current context" 'public enum ExperienceLevel {......} (in the model)public ExperienceLevel ExpLevel{get;set;} (in the view)@Html.RadioButtonFor(m=>m.ExpLevel, (int)ExperienceLevel.GreenCircle);' It gives me the error on ExperienceLevel.GreenCircle
Scratch that, found a solution. Thanks a bunch, it worked out perfectly. I've got my list of RadioButtons. Now I just need to work out how to get the value of the chosen RadioButton in my controller to work with it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.