好吧。我對這種瘋狂感到非常沮喪。與@ Html.RadioButtonFor()一起使用的MVC模型綁定以及枚舉
我有一個4張單選按鈕的表單,基於我的自定義枚舉。
枚舉看起來是這樣的:
public enum PhoneSelector
{
PrivatePhone = 0,
WorkPhone = 1,
PrivateCellPhone = 2,
WorkCellPhone = 3
}
我的視圖模型的相關部分看起來是這樣的:
public class PersonPageViewModel
{
public PersonPageForm PersonPageForm { get; set; }
}
public class PersonPageForm
{
public List<PhoneSelector> PhoneSelectors { get; set; }
public PhoneSelector SelectedPhoneType { get; set; }`
}
視圖模型的人口:
PersonPageForm = new PersonPageForm
{
PhoneSelectors = Enum.GetValues(typeof(PhoneSelector)).OfType<PhoneSelector>().ToList(),
},
然後在我查看我的代碼如下:(內部爲Html.BeginForm()
)
@for (var i = 0; i < Model.PersonPageForm.PhoneSelectors.Count(); i++)
{
var currentValue = Model.PersonPageForm.PhoneSelectors[i];
<div class="row" style="@(string.IsNullOrWhiteSpace(userFields[i]) ? "display:none;" : string.Empty)">
<div class="large-6 columns">
@Html.RadioButtonFor(x => x.PersonPageForm.SelectedPhoneType, currentValue, new {id = currentValue, Name = currentValue})
@Html.LabelFor(x => @currentValue, Html.Translate("/radiobuttonlist/" + @currentValue) + " (" + @userFields[i] + ")", new {style = "font-weight: normal !important;"})
</div>
</div>
}
最後,控制器看起來是這樣的:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(PersonPageForm personPageForm, List<String> roleList, List<Int32> categoryList, String organizationType, HttpPostedFileBase userProfileImage)
這裏的問題是,每次提交達到我的ActionResult,personPageForm.SelectedPhoneType
設置爲PhoneSelector.PrivatePhone
。模型綁定器似乎沒有得到我想要在這裏做的。 有人可以提供有關此解決方案的一些信息,以及爲什麼它不能按預期工作。
我也試着用更簡單的方法...
@Html.RadioButtonFor(x => x.PersonPageForm.SelectedPhoneType, PhoneSelector.PrivateCellPhone, new {id = Guid.NewGuid()})
@Html.RadioButtonFor(x => x.PersonPageForm.SelectedPhoneType, PhoneSelector.PrivatePhone, new { id = Guid.NewGuid() })
@Html.RadioButtonFor(x => x.PersonPageForm.SelectedPhoneType, PhoneSelector.WorkCellPhone, new { id = Guid.NewGuid() })
@Html.RadioButtonFor(x => x.PersonPageForm.SelectedPhoneType, PhoneSelector.WorkPhone, new { id = Guid.NewGuid() })
...但還是結束了相同的結果。