开发者

ASP.net MVC 2.0 model binding - creates empty child objects

I 开发者_如何学JAVAhave an asp.net MVC application that was recently upgraded from 1.0 to 2.0. I use a Linq-to-Sql data model and in a lot of cases, I have been using these as my model objects, as it was simple and seemed to work...

I have a class that has foreign key relationships with two child tables - these child tables will not always be populated (i.e. the foreign key is nullable).

My code (a little simplified) looks something like this:

/// This would be the generated linq-to-sql class
public class ModelObject
{
    //Bunch of properties

    public ChildObject { get; set; }

    public ChildObject2 { get; set; }
}

public ActionResult Edit(int ID)
{
    //Get the current saved object
    ModelObject test = _service.GetModelObject(ID);

    UpdateModel(test);
}

Since the upgrade to 2.0, I've found that the updateModel call has been instantiated the two child objects - my save then fails, as some of these have empty fields which are not nullable. This wasn't happening previous to the upgrade.

Is there a way to stop this from happening (or does anybody have a pointer as to why this has started to happen since the upgrade)?


You can stop this from happening by specifying the properties you want to exclude from binding as a parameter in your UpdateModel() call:

UpdateModel(test, null, null, new [] { "ChildObject", "ChildObject2"});

You can get more information from MSDN.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜