从JSON数组到'model.UserId'的ID后值

时间:2013-10-03 09:53:17

标签: asp.net-mvc arrays json asp.net-mvc-4 arraylist

JSON Arrary如下

[
  {
    "id":1,
    "Name":"hvhv",
    "Marks":11,
    "Grade":"hvh"
  },
  {
    "id":2,
    "Name":"f",
    "Marks":12,
    "Grade":"yf"
  },
  {
    "id":3
    "Name":"ds",
    "Marks":13,
    "Grade":"jhj"
  }
]

我想在我的控制器的Method as Model / string Array

中使用此数组中的所有ID

我有一个名为registerModel的RegisterModel对象 我想张贴所有 id to registerModel.UserId 和name to registerModel.Name

2 个答案:

答案 0 :(得分:1)

如果您在控制器操作中收到此类JSON,则可以尝试按如下方式使用它。 创建类似的模型:

public class MyModel
{
 public int id {get; set;}
 public string Name {get; set;}
 public int Marks {get; set;}
 public sytring Grade {get; set;}
}

然后在您的Controller操作中:

public ActionResult MyAction (List<MyModel> models)
{
  foreach(var item in models)
  {
    var result = new registerModel 
      {
        name = item.Name,
        userID = id
       }
      //Do somthing with registerModel
   }
}

答案 1 :(得分:1)

您可以从HttpContext.Request对象接收json到您的模型列表,如

        public ActionResult MyAction()
        {
            var resolveRequest = HttpContext.Request;
            List<RegisterModel> registerModelList = new List<RegisterModel>();
            resolveRequest.InputStream.Seek(0, SeekOrigin.Begin);
            string jsonString = new StreamReader(resolveRequest.InputStream).ReadToEnd();
            if (jsonString != null)
            {
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                registerModelList = (List<RegisterModel>)serializer.Deserialize(jsonString, typeof(List<RegisterModel>));
            }
         }