Hal
Hal

Reputation: 1264

Passing an Anonymous Type to UpdateModel/TryUpdateModel in ASPNETMVC

Given the following controller method:

    [AcceptVerbs("POST","GET")]
    public ActionResult apiMapInfo()
    {
        var x = new { Lat = "", Long = "", Name = ""};
        var mapInfo = new DALServices.Models.MapInfo();

// Updates correctly

        TryUpdateModel(mapInfo); 

// Does not update correctly

        TryUpdateModel(x); 

        var svc = new APIServices.Services.ReturnMapInfo() {inputs = mapInfo};
        svc.Run();
        return new ObjectResult<Result>(new Result(svc.errorCode, svc.errorMessage, svc.results), svc.ExtraTypesForSerialization);
    }

The object x is not updated correctly by the TryUpdateModel method, but the mapInfo object is.

My assumption is that the TryUpdateModel method doesn't handle mapping to an anonymous type like x.

Thanks,

Hal

Upvotes: 2

Views: 649

Answers (3)

tvanfosson
tvanfosson

Reputation: 532605

Anonymous types have readonly properties and thus there is no public settor available for TryUpdateModel to change the property value.

Upvotes: 3

Craig Stuntz
Craig Stuntz

Reputation: 126587

Anonymous types are immutable. Hence, they cannot be updated.

Upvotes: 4

Chad Moran
Chad Moran

Reputation: 12854

I'm guessing because UpdateModel and TryUpdateModel that it's looking for properties and reflection on anonymous types might be a bit different. Either way the easiest thing to do would just create a concrete type.

Upvotes: 1

Related Questions