Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3 RadioButtonFor with enum

I'm having problems with the HtmlHelper, RadioButtonFor and an enum in my model. I have a strongly typed view, and I want the checkboxes to toggle my enum property.

Enum.cs

public enum Values{
    Value1,
    Value2
}

Model.cs

public class Model{
    public Values MyProp{ get; set; }
;

View.cshtml

@Html.RadioButtonFor(model => model.MyPropi, Values.Values1)

Controller.cs
public ActionResult WizardFirstStep()
{
    var model = new Model();
    return View(model);
}

If I set the MyProperty value in the controller, the RadioButton is checked as expected. But after a post to the next wizard step, which gets the model as parameter, the property isn't set.

If it will help you to understand what I mean: If it would be C# and WPF I would use a IValueConverter.

btw: I use a HtmlHelper.ActionLink to get the model to the controller.

Thanks in advance

like image 781
csteinmueller Avatar asked Dec 13 '12 16:12

csteinmueller


2 Answers

Try this, it should work as I have done the same thing before:

@Html.RadioButtonFor(model => model.MyProp, (int)Values.Values1, model.MyProp == Values.Values1)

Notice the cast to int, it ensures the correct value is used for html.

EDIT: Sorry, I think you also need the third parameter to ensure the correct radio button is set when loading the view.

I also assumed MyPropi was a typo and changed it to MyProp, please ensure this matches up correctly at your end

like image 133
musefan Avatar answered Oct 26 '22 23:10

musefan


Sorry for any inconvenience. After posting here, I found the solution very quickly. My ActionLink was not submitting the @Html.BeginForm form. So i changed my radiobutton to:

@Html.RadioButtonFor(model => model.MyPropi, Values.Values1, new{ onClick = "this.form.submit();" })

which submits the correct value to my controller. For the moment this is okay. Maybe the ActionLink can post back the form data.

like image 41
csteinmueller Avatar answered Oct 27 '22 01:10

csteinmueller