Geeks With Blogs

News profile for Aligned at Stack Overflow, Q&A for professional and enthusiast programmers

Donate Bitcoins

Check out Elapser from T3rse!
"free in Christ Jesus from the law of sin and death." Romans 8:2 (ESV) Check out the Falling Plates video on YouTube.
more about the Gospel
And then listen to Francis Chan speaking at LifeLight in SD.

Programming and Learning from SD

I needed to pass some data from JavaScript to my WebAi Controller and came across Rick Strahl's passing multiple POST parameters to Web API article, his use of the JObject from Json.Net and dynamics works really well. Note usage of the jsondata[“UserId”].Value<int>();. This is a simplified example of the code I‘m using.

Note: you can also return the JObject.

System.Web.Mvc.HttpPost]
public HttpResponseMessage UpdateUserInfo(JObject jsonData)
{
  // http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling
  // http://www.west-wind.com/weblog/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods
  int userId = 0;
  string firstName = string.Empty;
  try
  {
    userId = jsonData["UserId"].Value<int>();
    firstName = jsonData["FirstName"].Value<string>();
    
    if (userId == 0)
    {
      throw new ArgumentException("User Id is required.");
    }

    if (string.IsNullOrWhiteSpace(firstName))
    {
      throw new ArgumentException("firstName is required and cannot be empty.");
    }
    
    // get the 
    var user = this.UserRepository.GetById(userId);
    if (user == null)
    {
      throw new ArgumentException("The user with user id " + userId + " does not exist.");
    }
    user.FirstName = firstName;
    bool isSuccess = this.UserRepository.Update(user);
    if (!isSuccess)
    {
      throw new Exception("The user with user id: " + userId + " did not update successfully.");
    }
     return this.Request.CreateResponse(HttpStatusCode.OK);
  }
   catch (Exception ex)
  {
    // my log4Net logger, it's been injected into the controller
    this._logger.Warn(string.Format("Error in UpdateUserInfo userId:{1}, new firstName: {2}",  userId, firstName), ex);
    throw new HttpResponseException(new HttpResponseMessage
                    {
                      StatusCode = HttpStatusCode.InternalServerError,
                      Content = new StringContent(Resource.UpdateUserErrorMessage)
                    });
  }
}  

 

Here’s how I’m calling it from JavaScript:

var data = {};
data.AssetId = assetId;
data.FirstName = alias;
data.UserId = userId;

saveFirstNameChange = function (firstName, userId, callback) {
 var data = {};
data.FirstName = alias;
data.UserId = userId;
  $.ajax({
  type: "POST",
  url: 'http://localhost/' + 'updateUserInfo',
  data: data,
  dataType: "json",
  success: function (result, textStatus) {
    callback("success: " + textStatus);
  },
  error: function (jqXHR, textStatus) {
    // textStatus: "timeout", "error", "abort", "parsererror"
    callback("error: " + textStatus);
  }
  });
}};

You can also use the ToObject method for more complex types as shown in the answer to this question.

Posted on Thursday, January 17, 2013 3:21 PM MVC , JavaScript | Back to top


Comments on this post: Using Json.Net JObject with WebApi GET Requests

# Removal companies
Requesting Gravatar...
It’s really a nice and useful piece of information. I am happy that you simply shared this useful information with us. Please stay us informed like this. Thanks for sharing.
Left by laila smart on Jan 17, 2013 11:48 PM

Your comment:
 (will show your gravatar)


Copyright © Aligned | Powered by: GeeksWithBlogs.net | Join free