Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • JObject Class

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 472
    Comment on it

    Namespace: Newtonsoft.Json.Linq

    In web api sometimes we often need to send multiple parameters to controller's action(method). In that case we can create model of multiple parameters and wrap multiple parameters to JSON and send it to action(method). Another way is to receive JSON into JObject.

    Example

    var Obj = {
                Id: 1,
                Name: "Priyank",
    };
    $http.post('api/Student/Create', Obj);

    Here, I want to send Id and Name to action(method). To send multiple values we must wrap values into JSON. Here, Id and Name are wrapped into Obj which is a JSON object.

    1) Receiving JSON as Model

    First way is to create model of properties we want to post to controller.

    //Model
    public class Student
    {
       public int Id;
       public string Name;
    }
    
    //Method inside Student controller
    [HttpPost]
    public void Create(Student student)
    {
       int Id = student.Id;
       string name = student.Name;
    }

    2) Receiving  JSON as JObject

    It is not always good to create model of properties. Model should be created only if it used anywhere else as well like Business Logic layer or Data access layer etc. If we have to send different number of parameters each time then we should avoid creating model each time instead use JObject class.

    [HttpPost]
    public void Create(JObject student)
    {
        dynamic studentObj = student;
        int Id = Convert.ToInt32(studentObj.Id.Value);
        string name = Convert.ToString(studentObj.Name.Value);
    }

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: