【问题标题】:RadioButton list Binding in MVC4MVC4 中的 RadioButton 列表绑定
【发布时间】:2015-12-07 18:44:31
【问题描述】:

我有一个单选按钮列表,它绑定来自 Enum 类的数据,并且它在视图中正常工作。

但我担心的是如何将单选按钮的初始值设置为CROCount.ONE。我尝试通过以下方式设置初始值但无法获得所需的结果。

public enum CROCount
    {
        ONE = 1,
        TWO = 2
    }

ViewModel 是

public class RegistraionVM
{      
    ....  
    public EnumClass.CROCount CROCount { get; set; }       
}

我生成的单选按钮列表如下。

<div>
    @foreach (var count in Enum.GetValues(typeof(SMS.Models.EnumClass.CROCount)))
    {
         <label style="width:75px">
              @Html.RadioButtonFor(m => m.RegistrationVenue, (int)count, 
              new { @class = "minimal single" })
              @count.ToString()
         </label>
    }
</div>

在控制器中执行的绑定是

public ActionResult Index(int walkInnId)
    {
        try
        {
            var _studentReg = new RegistraionVM
            {
               CROCount=EnumClass.CROCount.ONE                   

            };                               
            return View(_studentReg);
        }
        catch (Exception ex)
        {
            return View("Error");
        }

    }

【问题讨论】:

  • 使用RadioButtonFor(m =&gt; m.RegistrationVenue, count, ...) - 删除(int)
  • 试过那个伙伴但没用..
  • 为我工作 - 你应该生成&lt;input type="radio" value="ONE" /&gt;(和value="TWO"
  • 对不起,应该是RadioButtonFor(m =&gt; m.CROCount, count, ....)
  • 但是在m.RegistrationVenue之后我无法导航到CROCount..

标签: asp.net-mvc-4 data-binding enums radiobuttonlist


【解决方案1】:

您将单选按钮绑定到属性CROCount(不是RegistrationVenue),因此您的代码应该是

@Html.RadioButtonFor(m => m.CROCount, count, new { id = "", @class = "minimal single" })

请注意,第二个参数是count(不是(int)count),以便生成value="ONE"value="TWO"。另请注意,new { id = "", 删除了 id 属性,否则会导致重复的 id 属性无效 html。

【讨论】:

猜你喜欢
  • 2013-05-26
  • 2017-05-10
  • 2013-08-22
  • 1970-01-01
  • 2012-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多