Model Binding on Multiple Model Form Submission from Strongly-Typed View

前端 未结 5 1462
情歌与酒
情歌与酒 2021-01-31 23:05

I\'m having problems binding on a form with multiple models being submitted. I have a complaint form which includes complaint info as well as one-to-many complainants. I\'m tr

5条回答
  •  一生所求
    2021-01-31 23:44

    I worked around the ModelBinding exception by doing the following:

    // Remove the error from ModelState which will have the same name as the collection.
    ModelState.Remove("Complaints"/*EntityCollection*/); 
    if (ModelState.IsValid) // Still catches other errors.
    {
        entities.SaveChanges(); // Your ObjectContext
    }
    

    The main drawback is that the exception is still thrown and that can be expensive at runtime. The elegant work around may be to create a wrapper around the existing DefaultBinder and prevent it from instantiating the EntityCollection again, which is already done by EF. Then binding that collection to the form values (FormCollection).

    Keep in mind if you're binding more than one collection, you will need to remove the error for each collection.

    In my experiment, the collection saved successfully as well as the root object in the graph which the collection was part of.

    Hope that helps someone else.

提交回复
热议问题