简体   繁体   English

带有枚举的MVC3 RadioButtonFor

[英]MVC3 RadioButtonFor with enum

I'm having problems with the HtmlHelper, RadioButtonFor and an enum in my model. 我遇到了HtmlHelper,RadioButtonFor和我模型中的枚举问题。 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. 如果我在控制器中设置MyProperty值,则按预期检查RadioButton。 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. 如果它能帮助你理解我的意思:如果它是C#和WPF我将使用IValueConverter。

btw: I use a HtmlHelper.ActionLink to get the model to the controller. 顺便说一句:我使用HtmlHelper.ActionLink将模型送到控制器。

Thanks in advance 提前致谢

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. 注意转换为int ,它确保正确的值用于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 我还假设MyPropi是一个拼写错误并将其更改为MyProp ,请确保在您的最后匹配正确

Sorry for any inconvenience. 任何不便敬请谅解。 After posting here, I found the solution very quickly. 在这里发布后,我很快找到了解决方案。 My ActionLink was not submitting the @Html.BeginForm form. 我的ActionLink没有提交@ Html.BeginForm表单。 So i changed my radiobutton to: 所以我将我的radiobutton改为:

@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. 也许ActionLink可以回发表单数据。

对于Aspx页面:<%:Html.RadioButtonFor(m => m.YourProp,您的枚举的选定值,如:demo1.enum1.value2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM