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.