I have the following snippets in my MVC 3 website.
Model:
public class Item1
{
[Display(Name = "Family name")]
public string FamilyName { get; set; }
[Display(Name = "Given name")]
public string GivenName { get; set; }
}
Controller method:
public string SaveAsIs(string form_section11)
{
// method 1 works
var viewModel = new JavaScriptSerializer().Deserialize<IDictionary<string, object>>(form_section11);
// method 2 gives empty viewModel2
var viewModel2 = new JavaScriptSerializer().Deserialize<Item1>(form_section11);
// method 3 gives empty item1
Mapper.CreateMap<IDictionary<string, object>, Item1>();
Item1 item1 = Mapper.Map<IDictionary<string, object>, Item1>(viewModel);
}
And the value I am posting back is a JSON.stringified structure representing my model. The string (laid out for readability) appears as:
"{
\"item1.FamilyName\":\"Smith\",
\"item1.GivenName\":\"Jane\"
}"
What I want to do is to convert the stringified JSON to my model but cannot see how to do beyond the two attempts above or write my own serializer :-(
Everything else works fine. Anyone got any other ideas. Thanks.
UPDATE 1
Thanks to Darin I have a partial solution which is to remove item1. before using JavaScriptSerializer as above. The strange thing is that item1. is added by Razor, MVC 3 etc when using a strongly typed model. Anyway I now have a solution - thanks.
UPDATE 2
In answer to Darin's question below, Item1 is one entity in my model. The model looks like:
public class ItemModel
{
public Item1 item1 {get; set;}
public Item2 item2 {get; set;}
}
The view uses @model ItemModel with the field as @Html.EditorFor(m => m.item1.FamilyName). The two entities are in different forms on the same screen and I am returning them as
var form_section1Data = JSON.stringify($("#form_section1").formParams()); //item1
var form_section1Data = JSON.stringify($("#form_section1").formParams()); //item2
and the Ajax call contains:
data: JSON.stringify({
form_section1: form_section1Data,
form_section2: form_section2Data
}),
I simplified the initial question (trying to be helpful :-))