简体   繁体   中英

Asp.Net Core [Bind] ,how to use it?

public class TestBind
{
    public string A { get; set; }
    public string B { get; set; }
    public string C { get; set; }
    public string D { get; set; }
    public string E { get; set; }
    public string F { get; set; }
    public string G { get; set; }
}

[HttpPost("hhh")]
public async Task<JsonResult> HHH([Bind("A,B,C")] TestBind test)
{

}

What's the difference between [Bind("A,B,C")] and [Bind("A,B,C,D,E,F,G")] ?

I have tested it many times and found no difference.

What's the difference between [Bind("A,B,C")] and [Bind("A,B,C,D,E,F,G")]?

The former tells the model binder to include only the properties of TestBind named A , B and C . The latter tells the model binder to include those same properties plus D , E , F and G .

Are you testing by posting data for all properties of your model? You should notice that the values you post for the excluded properties are not bound.

[Bind] attribute can be applied to a class or a method parameter.Tells the model binder to only populate properties with names specified.

So in [Bind("A,B,C")] only the A, B and C properties will be populated. All others will be ignored.

The [Bind] attribute can be used to protect against overposting in create scenarios. It doesn't work well in edit scenarios because excluded properties are set to null or a default value instead of being left unchanged. For defense against overposting, view models are recommended rather than the [Bind] attribute.

See here for more details : https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-2.2#attributes-for-complex-type-targets

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM