Reputation: 3200
I am getting this long error when i accpet the parameter as dynamic on my server side action method in mvc 4.
{"Message":"An error has occurred.","ExceptionMessage":"'Newtonsoft.Json.Linq.JObject' does not contain a definition for 'TournamentId'","ExceptionType":"Microsoft.CSharp.RuntimeBinder.RuntimeBinderException","StackTrace":" at CallSite.Target(Closure , CallSite , Object )\r\n at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)\r\n at ManagerDeTorneos.Web.Controllers.TournamentDateController.Create(Object data) in F:\Prince\Projects\Juan\trunk\ManagerDeTorneos.Web\Controllers\TournamentDateController.cs:line 133\r\n at lambda_method(Closure , Object , Object[] )\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c_DisplayClass13.b_c(Object instance, Object[] methodParameters)\r\n at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)\r\n at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken)"}
[HttpPost]
public HttpResponseMessage AddMatch(dynamic data)
{
int tournamentDateId = (int)data.TournamentDateId.Value;
var tournamentDate = Catalog.TournamentDateRepository.GetById(tournamentDateId);
if (tournamentDate == null)
{
throw ExceptionHelper.NotFound("Fecha no encontrada!");
}
In The above method data Contains tournamentId as sent from ajax call as JSON.Stringify({'TournamentId':'5'}).
Can anybody tell me what is the cause of error. I even replaced the dll of Newtonsoft.Json as well
Upvotes: 1
Views: 568
Reputation: 3200
You are right dan but i fixed my issue by removing that dll from GAC. May be in GAC it was using old assembly
Upvotes: 1
Reputation: 9847
The error is caused by the fact that you typed your parameter as dynamic
, which means that the model binder doesn't know what to make it. It's the same as if you were to declare it as an object
. Since you are providing JSON, it serializes the object as a Json.Net JObject
. Just because you define it as a dynamic
doesn't mean that it's going to magically take whatever shape you need it to.
Change it to a concrete type - something that matches the structure of the provided JSON:
public class TournamentInfo
{
public int TournamentId { get; set; }
}
[HttpPost]
public HttpResponseMessage AddMatch(TournamentInfo data)
{
int tournamentDateId = data.TournamentId;
var tournamentDate = Catalog.TournamentDateRepository.GetById(tournamentDateId);
if (tournamentDate == null)
{
throw ExceptionHelper.NotFound("Fecha no encontrada!");
}
This way, the binder knows what it's supposed to turn the JSON into, and since TournamentInfo
matches the structure of the JSON, it won't have any trouble serializing it.
Don't misuse dynamic
. It was not introduced into C# so developers could stop defining classes.
Upvotes: 0