如果BindProperty不能正常工作,可能是因为它不适用于嵌套对象。在这种情况下,可以使用Bind不带后缀的版本,并对每个属性进行绑定。以下是一个示例:
public class ParentClass
{
public ChildClass Child { get; set;}
}
public class ChildClass
{
public string Name { get; set; }
}
public class IndexModel : PageModel
{
[BindProperty]
public ParentClass Parent { get; set; }
public async Task OnPostAsync()
{
var childName = Parent.Child.Name;
// do something with childName
}
public async Task OnGetAsync()
{
Parent = new ParentClass
{
Child = new ChildClass
{
Name = "John"
}
};
}
}
在此示例中,使用[BindProperty]尝试绑定Parent对象将失败。相反,需要手动绑定Parent和Child属性,如示例代码中所示。