use*_*982 12 c# asp.net-mvc asp.net-mvc-4
在我的项目中,我有一个模型,你可以在这里看到我模型的一部分:
public class CheckoutModel
{
public bool OtherPlace { get; set; }
[RequiredIf("OtherPlace", true, ErrorMessage = " ")]
public string OtherPlaceFullName { get; set; }
[RequiredIf("OtherPlace", true, ErrorMessage = " ")]
public int OtherPlaceProvinceId { get; set; }
[RequiredIf("OtherPlace", true, ErrorMessage = " ")]
public string OtherPlaceCity { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我使用RequiredIf属性在视图中验证我的模型,
if (!ViewData.ModelState.IsValid)
{
@Html.ValidationSummary(false)
}
Run Code Online (Sandbox Code Playgroud)
我填写了我的表单的所有属性,但是当未填充OtherPlaceProvinceId时,我得到以下验证错误.
值"on"对于OtherPlace无效.
更新:控制器在这里:
[HttpGet]
public ActionResult CheckoutAccount()
{
var model = OrderManager.Instance.GetCheckoutAccount();
return View("_CheckoutAccount", model);
}
[HttpPost]
public ActionResult CheckoutAccount(CheckoutAccountModel model)
{
return View("_CheckoutAccount", model);
}
Run Code Online (Sandbox Code Playgroud)
Sim*_*sey 35
OtherPlace是复选框吗?复选框的默认值是,on如果它被勾选,如果不是,则为空白.ModelBinder不理解这一点.
ASP.Net处理这个,如果你使用帮助,通过这样做:
<input type="checkbox" name="OtherPlace" value="true"/>
<input type="hidden" name="OtherPlace" value="false"/>
Run Code Online (Sandbox Code Playgroud)
模型绑定器现在将勾选出勾选的复选框,将其转换为布尔值并将其绑定到模型.
您还可以使用带有true/false值的单选按钮
Had*_*ifi -4
您应该将 OtherPlaceProvinceId 从 int 更改为 int?,
public int? OtherPlaceProvinceId { get; set; }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12761 次 |
| 最近记录: |