I have a strongly typed view with my viewmodel which contains an object Person and an List of Skills. Person is quite straightforward. I use Html Helpers like this @Html.TextBoxFor(m => m.Person.FirstName)
. I submit my form and get what I want.
The problem is my List of skills.
With an AJAX call i get a JSON result which is an array of Skills.
How should I send the combination of both the skills and the person to my HTTPPOST method?
I see two possibilities.
The one I favour, but have no idea on how to implement in the correct way: Somehow manage to get this JSON result into my viewmodel (
List<Skill> skilllist
) and use the standard submit button and receive it in my HTTPPOST method like this. (see inline comments)[HttpPost] public ActionResult RegisterPersonAndSkills(PersonSkillViewModel model) { // I can acces the Person object and its properties string firstname = model.Person.FirstName; // It would be awesome if I could access the list which used to be a JSONresult string skillname = model.SkillList[0].SkillName return null; }
Try transforming, serializing everything that's in the form (Person object part) into a JSON result, insert the array of skills json result I have into that serialized viewmodel and receive the model through the modelbinding way. With the same outcome as the post method above. Again I'm not sure on how to implement this and how to deal with the possible validation issues. It seems a lot of work to serialize every property of Person into JSON, and add the Person object and skill array to a JSON PersonSkillViewModel.
How would you solve this problem?
Or is it simply impossible to get both results in one parameter?
The simplest way to achieve your desired result #1, is to add the Skills Array you recieved in the AJAX call, to the DOM via hidden fields client side. You'll have to use the naming convention that the default model binder uses (I don't have VS open, but if you populate your Skills Array on the GET method and add a for each with a Html.HiddenFor<> you should see the syntax.)
So basically you will need some JS to process the JSON request client side and add it to the DOM... this is just a few lines with Jquery, but you didn't mention how your are getting the skills array Ajax request.
来源:https://stackoverflow.com/questions/6800469/question-about-json-and-serialization