我正在尝试实现一个包含单选按钮的网格状结构的表单。有四个单选按钮,其中一个可以选择。在模型中,我有一个Enum来保存这四个选项,模型参考了这个。
The Enum:
public enum HubType
{
Hub5 = 0,
Hub3 = 1,
Router = 2,
Others = 3,
}
模特:
public class Customer
{
public string ReferenceId { get; set; }
public CustomerType Type { get; set; }
public int ChangesMade = 0;
public DateTime MigrationDate { get; set; }
public bool MigrationDateChanged = false;
public List<SiteDetails> Sites = new List<SiteDetails>()
{
new SiteDetails { SiteAddress = "test address 1", Hub = HubType.Hub3 },
new SiteDetails { SiteAddress = "test address 2", Hub = HubType.Hub5},
new SiteDetails { SiteAddress = "test address 3", Hub = HubType.Router},
new SiteDetails { SiteAddress = "test address 4", Hub = HubType.Hub5}
};
}
SiteDetails.cs
public class SiteDetails
{
public String SiteAddress { get; set; }
public HubType Hub = HubType.Hub5;
}
最后是局部视图SiteDetails.cshtml
@model MyApp.Models.Customer
@using MyApp.Models.Enums
@{
var hubTypes = Enum.GetValues(typeof(HubType));
}
@using (Html.BeginForm("SiteDetails", "MyApp", FormMethod.Post))
{
@for(int site = 0; site < Model.Sites.Count; site++)
{
@Model.Sites[site].SiteAddress
@for (int hub = 0; hub < hubTypes.Length; hub++)
{
@Html.RadioButtonFor(m => m.Sites[site].Hub, hubTypes.GetValue(hub))
}
<input type="submit" class="button right" value="Save
}
}
当我提交页面时,我希望使用所选值填充模型属性,这现在不会发生。请帮助我探究我做错的地方,以及是否有更好的方法来做到这一点。提前谢谢!
答案 0 :(得分:0)
List<SiteDetails> Sites
和HubType Hub
是字段,而不是属性,因此DefaultModelBinder
无法设置值。你需要使它们成为属性
public class Customer
{
....
public List<SiteDetails> Sites { get; set; }
}
public class SiteDetails
{
....
public HubType Hub = { get; set; }
}
然后在控制器中(或在无参数构造函数中)分配这些值。另请注意,int ChangesMade
和bool MigrationDateChanged
也是字段,但您似乎没有在视图中使用这些字段。