当前位置: 首页 > 知识库问答 >
问题:

绑定属性的模型不起作用

岳嘉悦
2023-03-14

我有一个ASP. NET核心Web API。

一个endpoint,它接受一个名为搜索的模型。它有一个名为表达式类型查询的属性。这个表达式对象有子类。

public class Search {

public Expression Query{get;set;}
}

Public class Expression {
}

public class AndExpression {
  public IList<Expression> Expressions {get;set;}
}

public class MatchesExpression {
  public string FieldId {get;set;}
  public string Value {get;set;}
  public string Operator {get;set;}
}

我将以下JSON发布到我的endpoint(应用程序的内容类型/JSON)

{"查询":{"字段ID":"主体","值":"蛋糕","运算符":"匹配"}}

首先,查询参数只是基本表达式——一个多态性问题!

所以我以为是定制的模型活页夹。

我可以针对搜索对象设置一个模型绑定器,但您会注意到,AndExpression可以包含其他表达式对象,因此我想编写一个绑定器,可以绑定到搜索模型上的“查询”和AndExpression模型上的表达式等

我试图这样做:

public class Search
{

    [ModelBinder(BinderType = typeof(ExpressionBinder))]
    public Expression Query { get; set; }
}

  public class ExpressionBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            throw new NotImplementedException();
        }
    }




   public class ExpressionBinderProvider : IModelBinderProvider {
    public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
    
            if (context.Metadata.ModelType == typeof(Expression))
            {
                return new BinderTypeModelBinder(typeof(ExpressionBinder));
            }
    
            return null;
        }
    }

我在Startup类的configureServices方法中连接了这个活页夹。

我在ExpressionBinder中有一个断点,它没有击中!

我做错了什么?

另外,我可以对表达式列表使用[ModelBinder(BinderType=typeof(ExpressionBinder))]属性吗?

共有1个答案

彭高畅
2023-03-14

所以这是非常明确的https://github.com/aspnet/Mvc/issues/4553

如果应用FromBody属性,ModelBinder属性将不起作用!

 类似资料:
  • 我遵循了许多链接,找到了在表视图中显示复选框的解决方案。但我无法更改表视图中复选框的值。 链接如下:如何在JavaFX中将CheckBox添加到TableView中 模型类: FXML文件: 控制器类: 输出:

  • 我想通过使用@ConfigurationProperties注释将我的Application.Properties自动绑定到一个类中。首先,我尝试了@value注释,并能够将属性值注入类变量。但是,@ConfigurationProperties没有将属性注入到值中。 我的应用程序.属性: application.java ConfigBinder.java 输出: 这样的执行到底出了什么问题?

  • 我怎么能告诉Asp.Net Mvc Model Binder将有效载荷中的一些值绑定到POCO模型中的一些特定属性? 例如,我有一个POCO模型,它有两个属性:FirstName和LastName,但我得到的JSON对象有不同的名称,比如first_name_text和last_name_text。我使用了一个模型绑定器将first_name_文本绑定到POCO中的FirstName属性等。 我在

  • 我有一个带有一个提交按钮的表单,并在控制器中设置action to destroy方法。相同的代码适用于其他窗体和控制器,但不适用于此窗体和控制器。当我在Chrome中检查我的网页时,表单标签中的操作是错误的。 这是我的表格: 我通过设置\组织\公司控制器中的编辑方法访问此表单: 下面是设置\组织\公司控制器中的销毁方法:

  • 英文原文:http://emberjs.com/guides/templates/binding-element-attributes/ 除了普通文本,你可能也希望在模板中包含可以将其属性绑定到控制器的HTML元素。 例如,想象一下你的控制器中包含这样一个属性,它包含指向一幅图像的URL地址: 1 2 3 <div id="logo"> <img {{bind-attr src=logoUr