"JsonException: The JSON value could not be converted to NodaTime.Instant" NodaTime issue with ASP.NET Core 3.1 Razor Page web application - asp.net-core-3.1

In ASP.NET Core 3.1 Razor Page pure front end web application I received the below error.
Installed the following packages:
<PackageReference Include="System.Text.Json" Version="4.7.2" />
<PackageReference Include="EnumExtensions.System.Text.Json" Version="1.0.0" />
<PackageReference Include="NodaTime" Version="3.0.1" />
<PackageReference Include="NodaTime.Serialization.SystemTextJson" Version="1.0.0" />
Also set this in Startup:
services.AddRazorPages()
.AddJsonOptions(options =>
{
// options.JsonSerializerOptions.PropertyNamingPolicy = null;
// options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
// options.JsonSerializerOptions.DictionaryKeyPolicy = null;
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverterWithAttributeSupport(null, true, true, true, true));
//options.JsonSerializerOptions.IgnoreNullValues = true;
options.JsonSerializerOptions.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
options.JsonSerializerOptions.Converters.Add(NodaConverters.IntervalConverter);
options.JsonSerializerOptions.Converters.Add(NodaConverters.InstantConverter);
})
.AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRoute("/Login", "");
});
JsonException: The JSON value could not be converted to NodaTime.Instant. Path: $.data[0].created_at | LineNumber: 0 | BytePositionInLine: 261.
System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType)
System.Text.Json.JsonPropertyInfoNotNullable<TClass, TDeclaredProperty, TRuntimeProperty, TConverter>.OnRead(ref ReadStack state, ref Utf8JsonReader reader)
System.Text.Json.JsonPropertyInfo.Read(JsonTokenType tokenType, ref ReadStack state, ref Utf8JsonReader reader)
System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, ref Utf8JsonReader reader, ref ReadStack readStack)
System.Text.Json.JsonSerializer.ReadCore(Type returnType, JsonSerializerOptions options, ref Utf8JsonReader reader)
System.Text.Json.JsonSerializer.Deserialize(string json, Type returnType, JsonSerializerOptions options)
System.Text.Json.JsonSerializer.Deserialize(string json, JsonSerializerOptions options)
Here's the snippet of data it's trying to deserialize. If I switch from Instant to DateTimeOffset, it works "instantly" (pun intended :D)
{
"data": [
{
"created_at": "2020-08-09T22:10:26.274672Z",
"updated_at": "2020-08-13T02:22:02.640871Z",
}
],
"page": 1,
"size": 20,
"count": 1,
"total": 1,
"success": true,
"message": null
}
Note: this json data is a result of serialization of an object that does include CreatedAt & UpdatedAt properties of the type (NodaTime)Instant. I confirm it works nicely with an asp.net core 3.1 mvc api application.
Not sure why it's not working. (Perhaps, John Skeet can shed some light?)

After doing some research & ultimately remembering/realizing that JsonSerializerOptions cannot be set at global in the current version of System.Text.Json I was finally able to get it working as expected by building options right where I need them. Here's the code snippet in case anyone gets stuck like me in the future.
var jsonString = "{\"data\":[{\"id\":\"f606942c-4740-46a7-be6f-66ceb38c530b\",\"created_at\":\"2020-08-09T22:10:26.274672Z\",\"updated_at\":\"2020-08-13T02:22:02.640871Z\"}],\"page\":1,\"size\":20,\"count\":1,\"total\":1,\"success\":true,\"message\":null }";
JsonSerializerOptions options = new JsonSerializerOptions();
options.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb);
options.Converters.Add(new JsonStringEnumConverterWithAttributeSupport(null, true, true, true, true));
var response = JsonSerializer.Deserialize<Response>(jsonString, options);
public enum SampleType
{
TYPE_0,
TYPE_1
}
public class Sample
{
[JsonProperty("id")]
public string Id { get; set; } = System.Guid.NewGuid().ToString();
[JsonProperty("created_at")]
public Instant CreatedAt { get; set; }
[JsonProperty("updated_at")]
public Instant UpdateAt { get; set; }
[JsonProperty("type")]
public SampleType Type { get; set; }
}
public class Response
{
[JsonProperty("data")]
public IEnumerable<Sample> Data { get; set; }
[JsonProperty("page")]
public int Page { get; set; }
[JsonProperty("size")]
public int Size { get; set; }
[JsonProperty("count")]
public int Count { get; set; }
[JsonProperty("total")]
public int Total { get; set; }
[JsonProperty("success")]
public bool Success { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
}

Related

Missing type map configuration or unsupported mapping.while trying to assign the data to DTO object

I am using AutoMapper.Extensions.Microsoft.DependencyInjection. I am using the Automapper NuGet package: AutoMapper.Extensions.Microsoft.DependencyInjection (7.0.0) for ASP.NET Core 3.1 application.
Here goes my domain object: file ResourceGroup.cs
public class ResourceGroups
{
public string id
{
get;
set;
}
public int ResourceGroupId
{
get;
set;
}
public bool IsPublished
{
get;
set;
}
public int? Position
{
get;
set;
}
public string CreatedBy
{
get;
set;
}
public string CreatedDate
{
get;
set;
}
public string UpdatedBy
{
get;
set;
}
public string UpdatedDate
{
get;
set;
}
public int? ResourceGroupContentId
{
get;
set;
}
public int LanguageId
{
get;
set;
}
public string GroupName
{
get;
set;
}
}
Here goes my DTO object: file ResourceGroupDTO.cs
public class ResourceGroupDTO
{
public int ResourceGroupId
{
get;
set;
}
public int? Position
{
get;
set;
}
[JsonProperty("groupname")]
[RegularExpression(Constants.GeneralStringRegularExpression)]
public string GroupName
{
get;
set;
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Auto Mapper Configurations
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
}
);
IMapper mapper = mappingConfig.CreateMapper();
services.AddSingleton(mapper);
}
MappingProfile.cs
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<ResourceGroups, ResourceGroupDTO>();
CreateMap<List<ResourceGroups>, List<ResourceGroupDTO>>();
}
}
file ResourceGroupService.cs
public class ResourceGroupService : IResourceGroupService
{
private readonly DemoDbContext _dbContext;
private readonly ICommonService _commonService;
private readonly IMapper _mapper;
public ResourceGroupService(DemoDbContext dbContext, ICommonService commonService, IMapper mapper)
{
_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
_commonService = commonService ?? throw new ArgumentNullException(nameof(commonService));
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
}
public async Task<ResourceGroupDTO> GetResourceGroupDetailsAsync(int resourceGroupId, int languageId)
{
var resourceGroup = await _dbContext.ResourceGroups.Where(rg => rg.ResourceGroupId.Equals(resourceGroupId) && rg.IsPublished.Equals(true))
.Select(rg => new { rg.ResourceGroupId, rg.Position, rg.GroupName, rg.LanguageId })
.AsNoTracking().ToListAsync();
var resGroup = resourceGroup.FirstOrDefault(rg => rg.LanguageId.Equals(languageId));
return _mapper.Map<ResourceGroupDTO>(resGroup);
}
}
While debugging the above code I get the below error:
Missing type map configuration or unsupported mapping. \n \nMapping types : \
n<> f__AnonymousType4 ` 4 ->
ResourceGroupDTO \n<> f__AnonymousType4 ` 4
[
[System.Int32, System.Private.CoreLib, Version = 4.0 .0 .0 , Culture = neutral, PublicKeyToken = 7 cec85d7bea7798e] ,
[System.Nullable ` 1[
[System.Int32, System.Private.CoreLib, Version = 4.0 .0 .0 , Culture = neutral, PublicKeyToken = 7 cec85d7bea7798e] ] ,
System.Private.CoreLib , Version = 4.0 .0 .0 , Culture = neutral , PublicKeyToken = 7 cec85d7bea7798e ] , [System.String, System.Private.CoreLib, Version = 4.0 .0 .0 , Culture = neutral, PublicKeyToken = 7 cec85d7bea7798e] ,
[System.Int32, System.Private.CoreLib, Version = 4.0 .0 .0 , Culture = neutral, PublicKeyToken = 7 cec85d7bea7798e] ] ->
Author.Query.Persistence.DTO.ResourceGroupDTO \n -- ->AutoMapper.AutoMapperMappingException : Missing type map configuration or unsupported mapping. \n \nMapping types : \
n<> f__AnonymousType4 ` 4 ->
You're trying to map an anonymous type, i.e.
new { rg.ResourceGroupId, rg.Position, rg.GroupName, rg.LanguageId }
onto a ResourceGroupDTO, hence the error.
To quickly fix your error you could just change the above to
new ResourceGroupDTO { ResourceGroupId = rg.ResourceGroupId, Position = rg.Position, GroupName = rg.GroupName, LanguageId = rg.LanguageId }
and then add LanguageId to ResourceGroupDTO and get rid of the mapper.
But what you should really be using is ProjectTo and you should change your .FirstOrDefault to a .Where - to make your query more efficient, in the format shown below:
await _dbContext.ResourceGroups
.AsNoTracking()
.Where(/* Put your where here */)
.ProjectTo<ResourceGroupDTO>(_mapper.Configuration)
.FirstOrDefaultAsync();
You can also simplify your startup

Returning ObjectID as a string from ASP.NET Core

How to you get a string representation of the ObjectId returned via ASP.NET Core.
I have the following result of an action in my controller:
return new ObjectResult(new { session, user });
One of the user properties is the UserId that is of the ObjectId type.
However, this gets returned in the response as
"id": {
"timestamp": 1482840000,
"machine": 6645569,
"pid": 19448,
"increment": 5052063,
"creationTime": "2016-12-27T12:00:00Z"
}
I would like the response to simply be 58625d5201c4f202609fc5f3 that is the string representation of the same structure.
Are there any easy way to do this for all returned ObjectIds?
EDIT
Adding some more data
Here are the user class. ObjectId is MongoDB.Bson.ObjectId
public class User
{
public ObjectId Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string PasswordHash { get; set; }
public string PasswordSalt { get; set; }
}
The get method in my controller. Controller is Microsoft.AspNetCore.Mvc.Controller.
[HttpGet("{id}", Name = "GetUser")]
public async Task<IActionResult> Get(ObjectId id)
{
var user = await _repository.GetOne<User>(id);
if (user == null) return NotFound();
return new ObjectResult(user);
}
And this is the method from my repository:
public async Task<T> GetOne<T>(ObjectId id)
{
var collectionname = typeof(T).Name;
var collection = _database.GetCollection<T>(collectionname);
var filter = Builders<T>.Filter.Eq("_id", id);
var result = await collection.Find(filter).ToListAsync();
return result.FirstOrDefault();
}
You have to explicitly write a ObjectID to JSON convertor. Please check the link below:
https://stackoverflow.com/a/37966098/887976

How can I translate an href into a RequestDto using ServiceStack?

I'm building a ReST API that supports linked resource expansion, and I can't work out how to use ServiceStack's native binding capabilities to translate a URL into a populated 'request DTO' object.
For example, say my API allowed you to retrieve information about a band using this request:
GET /bands/123
< 200 OK
< Content-Type: application/json
{
"href": "/bands/123",
"name": "Van Halen",
"genre": "Rock",
"albums" {
"href" : "/bands/1/albums",
}
}
If you wanted to expand the band's album list, you could do this:
GET /bands/1?expand=albums
< 200 OK
< Content-Type: application/json
{
"href": "/bands/123",
"name": "Van Halen",
"genre": "Rock",
"albums" {
"href" : "/bands/1/albums",
"items": [
{ "href" : "/bands/1/albums/17892" },
{ "href" : "/bands/1/albums/28971" }
]
}
}
I'm using ServiceStack, and I'd like to perform this inline expansion by re-using existing service methods.
My ServiceStack response DTOs look like this:
public class BandDto {
public string Href { get; set; }
public string Name { get; set; }
public AlbumListDto Albums { get; set; }
}
public class AlbumListDto {
public string Href { get; set; }
public IList<AlbumDto> Items { get; set;}
}
public class AlbumDto {
public string Href { get; set; }
public string Name { get; set; }
public int ReleaseYear { get; set; }
}
My ServiceStack request/route objects are like this:
[Route("/bands/{BandId}", "GET")]
public class Band : IReturn<BandDto> {
public string Expand { get; set; }
public int BandId { get; set; }
}
[Route("/bands/{BandId}/albums", "GET")]
public class BandAlbums : IReturn<AlbumListDto> {
public int BandId { get; set; }
}
and the actual services that handle the requests are like this:
public class BandAlbumService : Service {
public object Get(BandAlbums request) {
return(musicDb.GetAlbumsByBand(request.BandId));
}
}
public class BandService : Service {
private IMusicDatabase db;
private BandAlbumService bandAlbumService;
public BandService(IMusicDatabase musicDb, BandAlbumService bandAlbumService) {
this.db = musicDb;
this.bandAlbumService = bandAlbumService;
}
public object Get(Band request) {
var result = musicDb.GetBand(request.BandId);
if (request.Expand.Contains("albums")) {
// OK, I already have the string /bands/123/albums
// How do I translate this into a BandAlbums object
// so I can just invoke BandAlbumService.Get(albums)
var albumsRequest = Translate(result.Albums.Href);
result.Albums = bandAlbumService.Get(albumsRequest);
}
}
In the example above, say I have calculated the string /bands/123/albums as the HREF of Van Halen's album list.
How can I now use ServiceStack's built-in binding capabilities to translate the string /bands/123/albums into a BandAlbums 'request' object that I can pass directly into the BandAlbumService, get back a populated BandAlbumsDto object and include it in my response object?
(and yes, I'm aware this probably isn't an optimal approach in terms of minimising database hits. I'm going to worry about that later.)
RestPath should be able to help you:
I think this should work:
var restPath = EndpointHostConfig.Instance.Metadata.Routes.RestPaths.Single(x => x.RequestType == typeof(AlbumRequest));
var request = restPath.CreateRequest("/bands/123/albums")

Invalid date with BreezeJS and Hottowel

i've a problem whit breeze returned DateTime... i've tried also to update BreezeJs to the latest version but nothing change. I use breezeJs with HotTowel SPA
Controller:
[BreezeController]
public class ContribuentiController : ApiController
{
readonly EFContextProvider<LarksTribContext> _contextProvider =
new EFContextProvider<LarksTribContext>();
[System.Web.Http.HttpGet]
public string Metadata()
{
return _contextProvider.Metadata();
}
// ~/api/todos/Todos
// ~/api/todos/Todos?$filter=IsArchived eq false&$orderby=CreatedAt
[System.Web.Http.HttpGet]
public IQueryable<Contribuente> Contribuenti()
{
if (_contextProvider.Context.Contribuente != null)
{
return _contextProvider.Context.Contribuente.Include("Residenze.Strada");//.Include("Residenze").Include("Residenze.Strada");
}
else
{
return null;
}
}
[System.Web.Http.HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
return _contextProvider.SaveChanges(saveBundle);
}
}
Model:
[Table(name: "Contribuenti")]
public class Contribuente
{
[Key]
public int Id { get; set; }
[MaxLength(30,ErrorMessage = "Il cognome non deve superare i 30 caratteri")]
public string Cognome { get; set; }
[MaxLength(35, ErrorMessage = "Il nome non deve superare i 35 caratteri")]
public string Nome { get; set; }
[MaxLength(16, ErrorMessage = "Il Codice fiscale non deve superare i 16 caratteri")]
public string CodiceFiscale { get; set; }
public virtual ICollection<Residenza> Residenze { get; set; }
}
[Table(name: "Residenze")]
public class Residenza
{
[Key, Column(Order = 0)]
public int Id { get; set; }
public int ContribuenteId { get; set; }
[ForeignKey("ContribuenteId")]
public Contribuente Contribuente { get; set; }
public DateTime? DataInizio { get; set; }
public int StradaId { get; set; }
[ForeignKey("StradaId")]
public Strada Strada { get; set; }
public int Civico { get; set; }
public string Interno { get; set; }
public string Lettera { get; set; }
}
[Table(name: "Strade")]
public class Strada
{
[Key]
public int Id { get; set; }
[MaxLength(20,ErrorMessage = "Il toponimo deve contenere al massimo 20 caratteri")]
public string Toponimo { get; set; }
[MaxLength(50, ErrorMessage = "Il nome deve contenere al massimo 50 caratteri")]
public string Nome { get; set; }
}
when i make this query:
var query = breeze.EntityQuery.
from("Contribuenti").expand(["Residenze"], ["Strada"]);
the json response is:
[{"$id":"1","$type":"LarksTribUnico.Models.Contribuente, LarksTribUnico","Id":1,"Cognome":"Manuele","Nome":"Pagliarani","CodiceFiscale":"HSDJSHDKHSD","Residenze":[{"$id":"2","$type":"LarksTribUnico.Models.Residenza, LarksTribUnico","Id":5,"ContribuenteId":1,"Contribuente":{"$ref":"1"},"DataInizio":"2012-12-10T22.00.00.000","StradaId":4,"Strada":{"$id":"3","$type":"LarksTribUnico.Models.Strada, LarksTribUnico","Id":4,"Toponimo":"Via","Nome":"Milano"},"Civico":0}]}]
But in result of query "DataInizio" is always marked as "Invalid date".
Any idea aout the problem?
Thanks
Breeze server side converts SQL Server DateTime to ISO 8601. In my code (breeze v0.72) dates seem to end up in UTC in SQL, and get converted back to local somewhere in breeze.
Check the Breeze docs on dates. http://www.breezejs.com/documentation/date-time
or, as suggested in the breeze docs, you can add moment.js to your project if HotTowel does not. https://github.com/moment/moment
Moment recognizes the JSON you are describing.
A moment() is different than a JavaScript date, but it is easier to manipulate and parse.
This code you the current browser date from moment.
var now = window.moment().toDate();
This code demonstrates how to turn an ISO into a JavaScript Date object through moment.
// ISO 8601 datetime returned in JSON.
// In your code, you would pull it out of your the
// return variable in your dataservice.js
var DataInizio = "2012-12-10T22.00.00.000"
// convert your variable to a moment so you can parse it
var momentdatainizio = window.moment(DataInizio);
// convert the ISO to a javascript Date object so you can use it in js.
var mydate = window.moment(DataInizio).toDate();
Your Stada will end up in the breeze Metadata store which you use to populate your viewModel.
Retrieve the strada from the Metadata store or the database with something like this code in your dataservice.js. I am being a little more verbose than necessary so you can debug.
var getStrada = function (stradaId, callback) {
var query = EntityQuery.from("Strada")
.using(manager);
var pred = new breeze.Predicate("idd", "eq", stradaId);
// create the query
var queryb = query.where(pred);
// check the MetadataStore to see if you already have it
var localsession = queryb.executeLocally();
if (localsession) {
if (localsession.length > {
window.app.vm.strada.strada(data.results);
return localsession;
}
}
// get it from the server
else {
// return the promise to prevent blocking
// then set your viewModel when the query fulfills
// then make your callback if there is one
// handle the fail in your queryFailed function if there is a problem
return manager.executeQuery(queryb)
.then(function (data) {
window.app.vm.strada.strada(data.results);
})
.then(function () {
if ((typeof callback !== 'undefined' && callback !== null)) {
callback();
}
})
.fail(function () {
queryFailed();
});
}
};
Here is a fragment of a ko viewModel in strada.js
app.vm.strada = (function ($, ko, dataservice, router) {
var strada = ko.observable();
...
return {
strada : strada,
...
})($, ko, app.dataservice, app.router);
Here is the custom binding handler for knockout in the ko.bindingHandlers.js. This code is slightly verbose so you can debug the intermediate variables.
window.ko.bindingHandlers.DataInizio = {
// viewModel is a Strada
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor(), allBindings = allBindingsAccessor();
var valueUnwrapped = window.ko.utils.unwrapObservable(value);
var $el = $(element);
if (valueUnwrapped.toString().indexOf('Jan 1') >= 0)
$el.text("Strada not Started");
else {
var date = new Date(valueUnwrapped);
var d = moment(date);
$el.text(d.format('MM/DD/YYYY'));
}
}
};
Here is the html for the binding handler
...
Strada DataInizio:
...
I wrote this code based upon my code using Breeze v0.72 which uses sammy.js as the router. Your mileage may vary with newer versions of breeze and Durandel.

Custom Model Binder, asp.net mvc 2 rtm 2, Parsing ID to ComplexModel

I have found myself with at little problem, and I think a custom model binder is the way to go.
My Domain model looks like this,readly standard
I got a Page and a Template. The Page has the Template as a ref.
So the Default asp.net mvc Binder, does not know how to bind it, therefore I need to make some rules for it. (Custom Model Binder)
public class PageTemplate
{
public virtual string Title { get; set; }
public virtual string Content { get; set; }
public virtual DateTime? Created { get; set; }
public virtual DateTime? Modified { get; set; }
}
public class Page
{
public virtual string Title { get; set; }
public virtual PageTemplate Template { get; set; }
public virtual string Content { get; set; }
public virtual DateTime? Created { get; set; }
public virtual DateTime? Modified { get; set; }
}
So I have Registreted the ModelBinder in globals.asax
ModelBinders.Binders.Add(typeof(Cms.Domain.Entities.Page),
new Cms.UI.Web.App.ModelBinders.PageModelBinder(
new Services.GenericApplicationService<Cms.Domain.Entities.Page>().GetEntityStore()
)
);
My ModelBinder tage a paremeter, witch is my Repository, where I get all my Entities ( Page, Template )
My Controller for a Page looks like this.
I have posted into a Create Controler, it does not matter for now, if it was a Update method.
Since I in this case have a dropdown, that represents the Template, I will get an ID in my form collection.
I then call: TryUpdateModel and I got a hit in my PageModelBinder.
[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Create(FormCollection form)
{
Page o = new Page();
string[] exclude = new { "Id" }
if (base.TryUpdateModel<Page>(o, string.Empty, null, exclude, form.ToValueProvider()))
{
if (ModelState.IsValid)
{
this.PageService.Add(o);
this.CmsViewData.PageList = this.PageService.List();
this.CmsViewData.Messages.AddMessage("Page is updated.", MessageTypes.Succes);
return View("List", this.CmsViewData);
}
}
return View("New", this.CmsViewData);
}
So I end op with the Model Binder.
I have search the internet dry for information, but im stock.
I need to get the ID from the FormCollection, and parse it to at Model from my IEntityStore.
But how ?
public class PageModelBinder : IModelBinder
{
public readonly IEntityStore RepositoryResolver;
public PageModelBinder(IEntityStore repositoryResolver)
{
this.RepositoryResolver = repositoryResolver;
}
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException("bindingContext");
}
if (modelType == typeof(Cms.Domain.Entities.Page))
{
// Do some magic
// Get the Id from Property and bind it to model, how ??
}
}
}
// Dennis
I hope, my problom is clear.
Did find a work around.
I download the sourcecode for asp.net r2 rtm 2
And did copy all code for the default ModelBinder, and code it need. Did some minor change, small hacks.
the work around is doing a little hack in this method:
[SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.Web.Mvc.ValueProviderResult.ConvertTo(System.Type)",
Justification = "The target object should make the correct culture determination, not this method.")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "We're recording this exception so that we can act on it later.")]
private static object ConvertProviderResult(ModelStateDictionary modelState, string modelStateKey, ValueProviderResult valueProviderResult, Type destinationType)
{
try
{
object convertedValue = valueProviderResult.ConvertTo(destinationType);
return convertedValue;
}
catch (Exception ex)
{
try
{
// HACK if the binder still fails, try get the entity in db.
Services.GenericApplicationService<Cms.Domain.Entities.PageTemplate> repo;
repo = new Services.GenericApplicationService<Cms.Domain.Entities.PageTemplate>();
int id = Convert.ToInt32(valueProviderResult.AttemptedValue);
object convertedValue = repo.Retrieve(id);
return convertedValue;
}
catch (Exception ex1)
{
modelState.AddModelError(modelStateKey, ex1);
return null;
}
}
}
This question is closed.