如果你想自定義綁定到它可以是這樣的:
public class BoolModelBinder : DefaultModelBinder
{
protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext,
PropertyDescriptor propertyDescriptor)
{
if (propertyDescriptor.PropertyType == typeof(bool))
{
Stream req = controllerContext.RequestContext.HttpContext.Request.InputStream;
req.Seek(0, SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
var data = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
string value = data[propertyDescriptor.Name];
bool @bool = Convert.ToBoolean(int.Parse(value));
propertyDescriptor.SetValue(bindingContext.Model, @bool);
return;
}
else
{
base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
}
}
}
但MVC和的WebAPI INT轉換爲bool(字段名稱必須相同),並且不需要任何額外的東西來寫,所以我不知道你是否需要上面的代碼。
試試這個演示代碼:
public class JsonDemo
{
public bool Bool { get; set; }
}
public class DemoController : Controller
{
[HttpPost]
public ActionResult Demo(JsonDemo demo)
{
var demoBool = demo.Bool;
return Content(demoBool.ToString());
}
}
和發送JSON對象:
{
"Bool" : 0
}
如果屬性是布爾,你爲什麼不使用'@ Html.CheckBoxFor(M => m.SomeBool )'?爲什麼請求包含「int」? –
@StephenMuecke我不希望'&foo = True',因爲我的用戶玩弄嘗試不同組合的查詢字符串。當它是一個整數時,它們不會。 –