2015-10-17 27 views
0

我可以用a custom model binder綁定在此操作的01falsetrue自定義模型在一個強類型的模型爲特定的屬性綁定

[IntToBoolBinder] 
public virtual ActionResult foo(bool someValue) { 
} 

但現在假設參數是一個強烈-typed型號:

public class MyModel { 
    public int SomeInt { get; set; } 
    public string SomeString { get; set; } 
    public bool SomeBool { get; set; }   // <-- how to custom bind this? 
} 

public virtual ActionResult foo(MyModel myModel) { 
} 

請求將包含一個int和我的模型需要一個bool。我可以爲整個MyModel模型寫一個定製模型活頁夾,但我想要更通用的東西。

可以自定義綁定強類型模型的特定屬性嗎?

+0

如果屬性是布爾,你爲什麼不使用'@ Html.CheckBoxFor(M => m.SomeBool )'?爲什麼請求包含「int」? –

+0

@StephenMuecke我不希望'&foo = True',因爲我的用戶玩弄嘗試不同組合的查詢字符串。當它是一個整數時,它們不會。 –

回答

2

如果你想自定義綁定到它可以是這樣的:

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 
} 
+0

所以這隻會綁定bool屬性,並讓所有其他人獨立? –

+1

是的,其他屬性將綁定與默認綁定 –

+0

你的意思是「不需要額外的東西寫」?有沒有自動完成的東西? –

相關問題