Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当我使用类类型作为参数时,为什么modelstate在我的razor页面中无效?_C#_Asp.net Core_Model Binding_Razor Pages - Fatal编程技术网

C# 当我使用类类型作为参数时,为什么modelstate在我的razor页面中无效?

C# 当我使用类类型作为参数时,为什么modelstate在我的razor页面中无效?,c#,asp.net-core,model-binding,razor-pages,C#,Asp.net Core,Model Binding,Razor Pages,这是我第一次尝试在ASP.Net Core 2.2中使用Razor页面,我正在使用页面过滤器来检查ModelState.IsValid,当我在OnGet()方法参数中使用导致页面失败的类型时,它在GET请求上返回false。如果我将方法的签名更改为使用基元类型,则模型状态有效 例如: 以下代码的ModelState.IsValid为false,在ASP.Net Core 2.2 MVC中的控制器操作中可以正常工作: public class IndexModel : PageModel {

这是我第一次尝试在ASP.Net Core 2.2中使用Razor页面,我正在使用页面过滤器来检查
ModelState.IsValid
,当我在
OnGet()
方法参数中使用导致页面失败的类型时,它在
GET
请求上返回false。如果我将方法的签名更改为使用基元类型,则模型状态有效

例如:

以下代码的
ModelState.IsValid
为false,在ASP.Net Core 2.2 MVC中的控制器操作中可以正常工作:

public class IndexModel : PageModel
{
    public string IsValid { get; set; }

    public void OnGet(Query query)
    {
        // FALSE
        IsValid = ModelState.IsValid.ToString();
    }

    public class Query
    {
        public int? Page { get; set; }
    }
}
但以下情况确实如此:

public class IndexModel : PageModel
{
    public string IsValid { get; set; }

    public void OnGet(int? query)
    {
        // TRUE
        IsValid = ModelState.IsValid.ToString();
    }
}
为什么会这样

Razor页面默认情况下仅使用非GET谓词绑定属性

参考文献

因为默认情况下,GET无法绑定到复杂对象。需要应用模型绑定属性

您必须明确地告诉它您要从哪里绑定

比如说

public void OnGet([FromQuery]Query query) {
   IsValid = ModelState.IsValid.ToString();
}

您可以将
Query
类型作为参数添加到
OnGet
方法,而不是将其作为PageModel属性添加,并使用
BindProperty
属性修饰:

public class IndexModel : PageModel
{
    public string IsValid { get; set; }

    [BindProperty(SupportsGet=true)]
    public Query query { get; set; }

    public void OnGet()
    {

    }

    public class Query
    {
        public int? Page { get; set; }
    }
} 
当使用
BindProperty
属性时,您必须选择在
GET
请求中进行绑定(因此
SupportsGet=true
),但是当您使用PageModel属性时,您不需要告诉模型绑定从何处获取值。它将自动搜索查询字符串、请求正文、路由数据等


更多信息:

因为默认情况下get无法绑定到复杂对象。需要应用模型绑定属性。绑定该对象的数据来自哪里?@Nkosi我已经编写了MVC应用程序,可以自动将查询字符串值绑定到复杂类型,没有问题,也没有模型绑定属性。这与razor页面不同。您必须明确地告诉它您要从哪里绑定。ie:
public void OnGet([FromQuery]Query Query Query)
这似乎对复杂类型不起作用:“错误CS0592属性'BindProperty'在此声明类型上无效。它仅对'property,indexer'声明有效。”在我看来,您试图将其应用于类,而不是属性。例如,您不能在页面模型上使用
BindProperty