我希望有人能够澄清模型应该如何通过回发进行,给出了下面的示例:
MyModel
public class MyModel
{
public string Text { get; set; }
public List<RadioButtonListItem> Options { get; set; }
public MyModel()
{
//Initialize the options.
this.Options = new List<RadioButtonListItem>()
{
//Setting Text, Value and Group Name. 3rd is selected by default.
new RadioButtonListItem("Item 1", "1", "Options"),
new RadioButtonListItem("Item 2", "2", "Options"),
new RadioButtonListItem("Item 3", "3", "Options", true)
};
}
}RadioButtonListItem
public class RadioButtonListItem
{
[HiddenInput]
public string Value { get; set; }
[HiddenInput]
public string Text { get; set; }
[HiddenInput]
public string GroupName { get; set; }
[HiddenInput]
public string SelectedValue { get; set; }
[TemplateVisibility(ShowForEdit = false)]
public override bool Selected { get { return string.Equals(this.Value, this.SelectedValue); } set { this.SelectedValue = (value ? this.Value : null); } }
public RadioButtonListItem() { }
public RadioButtonListItem(string value, string text, string groupName) : this(value, text, groupName, false) { }
public RadioButtonListItem(string value, string text, string groupName, bool selected)
{
//...
}
}摘要
在我看来,这似乎很奇怪,因为我并不认为您应该返回原始元数据,这样模型状态才能持久。但是如果你不把它送回去,你会怎么做?我只能想到另一个选项:在回发期间,创建第二个模型实例,并将用户的选择复制到新实例并将其反馈到视图中。
但在我看来这不对。有人能澄清一下这是怎么回事吗?
发布于 2011-09-30 13:43:20
当我问这个问题的时候,我没有想清楚。当然,列表中的项目不需要与post数据一起发回。您只需在模型中保留一个单独的列表,然后在构造函数中初始化该列表,然后有一个int字段,该字段是从列表中选择的项的ID或键。
模型如下:
[Required]
[DataType("RadioButtonList")]
[Display(Name = "Format", Order = 2)]
[AdditionalMetadata("Style", "Wide")]
[AdditionalMetadata("List", "Items")]
public int? SelectedItem { get; set; }
[TemplateVisibility(ShowForDisplay = false, ShowForEdit = false)]
public List<ListItem> Items { get; set; }它用AdditionalMetaData属性指向它自己的列表。因此,您可以轻松地将RadioButtonList EditorTemplate加载到列表中,只需将所选的项目发回。该值将在SelectedItem属性中填充。
https://stackoverflow.com/questions/7604973
复制相似问题