【问题标题】:Custom model binding for a particular property in a strongly-typed model强类型模型中特定属性的自定义模型绑定
【发布时间】:2015-10-17 17:50:24
【问题描述】:

我可以在此操作中使用a custom model binder01 绑定到falsetrue

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

但现在假设参数是一个强类型模型:

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 模型编写一个自定义模型绑定器,但我想要更通用的东西。

是否可以自定义绑定强类型模型的特定属性?

【问题讨论】:

  • 如果属性是bool,为什么不使用@Html.CheckBoxFor(m =&gt; m.SomeBool)?为什么请求会包含int
  • @StephenMuecke 我不想要&amp;foo=True,因为我的用户使用查询字符串尝试不同的组合。当它是 int 时,它们不会。

标签: c# asp.net asp.net-mvc model-binding


【解决方案1】:

如果您想对其进行自定义绑定,可以如下所示:

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 或 1 和 JSON 框架然后将其转换为 bool。 JSON 模型 - {"Test": 1},C# 模型 - public class Test {public bool Test {get;设置;}
  • 我为此添加了演示。请检查
  • 但记得在你的 Ajax 请求中将 Content-Type 设置为 application/json
  • 是的,但是这个活页夹适用于 MVC 项目 :) 但对我来说,我可以帮助你的最好的东西 :)
猜你喜欢
  • 1970-01-01
  • 2011-02-08
  • 1970-01-01
  • 1970-01-01
  • 2019-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
相关资源
最近更新 更多