Monday, April 11, 2011

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

From stackoverflow
  • 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.

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

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

0 comments:

Post a Comment