4
I have a situation where my HTML form represents a different data structure than the existing structure on the server.
To illustrate my problem, I will present a hypothetical situation, to present what solution I need:
My class:
public class Pessoa{
public long Codigo {get;set;}
public Estado Estado {get;set;}
}
[ModelBinder(typeof(EstadoBinder))]
public class Estado{
public static Estado ObtenhaEstado(long codigo){
// Obtêm instância de estado a partir do código
}
public long Codigo {get;set;}
}
My HTML:
<div id='formularioPessoa'>
<input type='text' name='Codigo' />
<input type='text' name='Estado' />
</div>
As you can see in the HTML snippet, I need the 'State' input to reflect the Status object of my Person class.
For the interaction of CLIENT to SERVER, I already managed a solution implementing a custom Binder, implementing the Imodelbinder interface. The solution was excellent, as it did not require any class other than the state itself to know this particularity.
My need:
Now, I need something to handle SERVER to CLIENT interaction, when there is a serialization of a C# object to a JSON object.
What I need is that, when serializing any object that contains a state property, this serializer knows that I must send a JSON in this structure (below, the example of the Person serialization):
{
"Codigo": "1",
"Estado": "2"
}
Instead of:
{
"Codigo": "1",
"Estado": {
Codigo: "2"
}
}
I have researched a lot of material in English, including searching for something associated with Datetime, in relation to 'Custom serializers', 'Override Json method of controller', however, I did not find any elegant solution like the solution I found for the interaction Client > Server (Imodelbinder).
A caveat:
- I cannot use Html Helpers or other ASP.NET MVC code in my CSHTML file.
You are using JSON.NET?
– Leonel Sanches da Silva
No Gypsy, use ASP.NET MVC 4 with all default modules.
– Joaquim Magalhães
There is the possibility of tying one Binder in the serialization object, but this only holds for JSON.NET: http://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_JsonSerializerSettings_Binder.htm. If it is possible to use, I put as a response.
– Leonel Sanches da Silva
Thanks Gypsy, I can include JSON.NET in my project yes! But I will need all the way if possible, because I do not know the library. From the inclusion in Nuget to the point of using it in the property.
– Joaquim Magalhães