【发布时间】:2011-06-08 04:09:24
【问题描述】:
我有一个模型,它有一个布尔属性和一些其他属性,这些属性具有 DataAnnotations 必需属性。
在我看来我有
@Html.CheckBoxFor(model => model.MyProduct.BloodTestEnabled, new { @class = "cb" })
但是,如果未选中该复选框,则值为 false,并且该值将回发到控制器,其中 MyProduct.BloodTestEnabled 的实例为 false,但因为它具有 MyProduct 的实例,所以 ModelState.IsValid 等于 false,因为必需的属性是被抓了。
如果复选框为真,我只希望它使用由模型绑定器创建的 MyProduct 的新实例回发到控制器。
我设法做的是修复它但不确定它是否正确:
public class MyViewModel
{
public MyProdct MyProduct
{
get;
set;
}
public bool BloodTestEnabled { get; set; }
}
public ActionResult Add(ProductViewModel newProducts)
{
if (!ModelState.IsValid)
{
return View("HomeIndex", newProducts);
}
//Some other code here
newProducts.MyProduct.BloodTestEnabled = newProducts.BloodTestEnabled;
_basket.AddProduct(newProducts.MyProduct);
}
【问题讨论】:
-
您可以使用具有您想要的行为的 html 复选框。 Htm.CheckBoxFor 呈现隐藏字段以发布未选中的值
标签: c# .net asp.net-mvc http asp.net-mvc-3