简体   繁体   中英

Partial Properties Binding/Posting in ASP.NET Core 2.1 MVC

I have a Model with 10 properties. This information is stored in a Database Table with 10 fields. Assuming each property matches with the table column.

I have a View which uses this Model. This View uses only 4 properties out of the 10 properties. The user will edit only these 4 properties. When I post it back. I get values only for these 4 properties as these are the only fields bound to the View. All other properties are null. I am not using any HTML hidden tags to bind other properties. So other properties are null in the [HttpPost] ControllerAction.

My question is,

Is there an easy way to identify out of these 10 properties which 4 properties are bound to the View and these are the only properties I need to update in the database.

In other words, does the "ModelState" know which properties are bound in the View ? Or is there some other class which will tell me exactly which fields are bound to that "View" so that I can write code to update only those fields in the database.

You may try a different approach to do this:

When you posting those 4 properties from the view for updating the model, use the identifier field of the model to get the data back from the db. This model returned from the db will have all 10 fields' information and you can update the 4 fields into this model. Then pass this updated model to the db for update operation.

Something like this:

public void Post(MyViewModel inputModel)
{
    var id = inputModel.Id;
    var dbModel = GetById(id);
    dbModel.Field1 = inputModel.Field1;
    dbModel.Field2 = inputModel.Field2;
    dbModel.Field3 = inputModel.Field3;
    dbModel.Field4 = inputModel.Field4;

    UpdateModelInDB(dbModel);
}

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