Question about JSON and Serialization

 ̄綄美尐妖づ 提交于 2019-12-07 22:34:39

问题


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.

  1. 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;
    }
    
  2. 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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!