访问IEnumerable mvc2单选按钮的值

时间:2011-12-13 08:26:20

标签: asp.net-mvc-2 radio-button ienumerable

我有一个是/否单选按钮,需要访问另一个aspx表单上的值。我不知道我这样做是否合适?

主视图模型

[UIHint("YesNoEditorTemplate")]
[DisplayName("Are you registered as blind (severely sight impaired)?")]
public IEnumerable<RadioButtonViewModel> RegBlind { get; set; }

单选按钮viewmodel

public class RadioButtonViewModel
{
    public string ID { get; set; }
    public string Name { get; set; }
    public int Value { get; set; }
    public string Text { get; set; }
}

控制器

List<RadioButtonViewModel> regBlindList = new List<RadioButtonViewModel>();
regBlindList.Add(CreateRadioButton("RegBlind", 1, "Yes"));
regBlindList.Add(CreateRadioButton("RegBlind", 0, "No"));
badgeViewModel.RegBlind = regBlindList;

编辑模板

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Tameside.Internal.ViewModels.BlueBadge.RadioButtonViewModel>>"%><%
foreach (var model in Model)
{%>
    <tr>    
        <td><%=String.Format("<input type=\"radio\" id=\"{0}\" name=\"{1}\" value=\"{2}\" />", model.ID, model.Name,model.Value)%></td>
        <td><%=String.Format("<label for=\"{0}\">{1}</label>", model.ID, model.Text)%></td>
    </tr><%
}%>

ASPX页面

<%=Html.EditorFor(x => x.RegBlind)%>

以下是我访问信息的方式

if (Model.RegBlind.First().Value == 0)

这是对的吗?

提前感谢您的帮助。

克莱尔

1 个答案:

答案 0 :(得分:2)

我认为问题在于,可枚举将永远不会存储所选择的值,而这只会在一定程度上丢失。

所以你需要两个部分,一个用来存储值,另一个用来包含你想要显示的单选按钮。

[DisplayName("Are you registered as blind (severely sight impaired)?")]
public int RegBlind { get; set; }

public IEnumerable<RadioButtonViewModel> RegBlindOptions { get; set; }

一旦你对它进行了排序,你应该能够将EditorTemplate用作部分视图(但是,这可能意味着将它从EditorTemplates目录移到相应的Views文件夹中或共享)。

<% Html.RenderPartial("YesNoEditorTemplate", Model.RegBlindOptions)%>

应该工作或接近。如果没有,请查看生成的HTML并检查一切是否正常,然后对POST标题中发回的内容有一个爱管闲事:)