[英]mvc5 model binding not working with dropdownlistfor
I have a view model class: 我有一个视图模型类:
public class TankDurationViewModel
{
public int selectedTankFactor { get;set; }
public List<SelectListItem> tank_factor_list { get; set; }
public double? myAnswer { get; set; }
public TankDurationViewModel()
{
this.tank_factor_list = new List<SelectListItem>();
this.tank_factor_list.Add(new SelectListItem { Text = "E", Value = "0.28" });
this.tank_factor_list.Add(new SelectListItem { Text = "H", Value = "3.14" });
}
}
View: 视图:
@Html.DropDownListFor(x=>x.selectedTankFactor,Model.tank_factor_list,"Tank Type")
When I submit, my selectedTankFactor will not bind. 当我提交时,我的selectedTankFactor将不会绑定。 I will always be 0. When i look at the formcollection, the selection is in the formcollection.
我将始终为0。当我查看formcollection时,选择位于formcollection中。 If I change the int selectedTankFactor into string, it will bind correctly but this it not what I want.
如果我将int selectedTankFactor更改为字符串,它将正确绑定,但这不是我想要的。 Does this relate to how i initialize the SelectListItem?
这与我初始化SelectListItem的方式有关吗? How do i get it to bind int?
我如何获得它绑定int? The SelectListItem only take string for value.
SelectListItem仅将字符串作为值。 Also how do i force user to choose a selection other than "Tank Type" before submitting?
另外,我如何强制用户在提交之前选择“坦克类型”以外的其他选择?
Make selectedTankFactor
to a decimal and if you don't want the user to submit form without selecting tank type, add required validation to selectedTankFactor property. 将
selectedTankFactor
设置为十进制,如果您不希望用户在不选择容器类型的情况下提交表单,则将必需的验证添加到selectedTankFactor属性。 You also have to include jquery validate library for client side validations . 您还必须包括用于客户端验证的 jquery validate库。
[Required]
public decimal selectedTankFactor { get;set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.