WebApi Routing to Action with Object Parameter [duplicate] - c#

I don´t know why my parameter "ParametroFiltro Filtro" is getting null, the other parameters "page" and "pageSize" is getting OK.
public class ParametroFiltro
{
public string Codigo { get; set; }
public string Descricao { get; set; }
}
My ApiController Get method:
public PagedDataModel<ParametroDTO> Get(ParametroFiltro Filtro, int page, int pageSize)
My ajax call:
var fullUrl = "/api/" + self.Api;
$.ajax({
url: fullUrl,
type: 'GET',
dataType: 'json',
data: { Filtro: { Codigo: '_1', Descricao: 'TESTE' }, page: 1, pageSize: 10 },
success: function (result) {
alert(result.Data.length);
self.Parametros(result.Data);
}
});

You are trying to send a complex object with GET method. The reason this is failing is that GET method can't have a body and all the values are being encoded into the URL. You can make this work by using [FromUri], but first you need to change your client side code:
$.ajax({
url: fullUrl,
type: 'GET',
dataType: 'json',
data: { Codigo: '_1', Descricao: 'TESTE', page: 1, pageSize: 10 },
success: function (result) {
alert(result.Data.length);
self.Parametros(result.Data);
}
});
This way [FromUri] will be able to pick up your complex object properties directly from the URL if you change your action method like this:
public PagedDataModel<ParametroDTO> Get([FromUri]ParametroFiltro Filtro, int page, int pageSize)
Your previous approach would rather work with POST method which can have a body (but you would still need to use JSON.stringify() to format body as JSON).

Provide the contentType property when you make the ajax call. Use JSON.stringify method to build the JSON data to post. change the type to POST and MVC Model binding will bind the posted data to your class object.
var filter = { "Filtro": { "Codigo": "_1", "Descricao": "TESTE" },
"page": "1", "pageSize": "10" };
$.ajax({
url: fullUrl,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(filter),
success: function (result) {
alert(result.Data.length);
self.Parametros(result.Data);
}
});

It's also possible to access POST variables via a Newtonsoft.Json.Linq JObject.
For example, this POST:
$.ajax({
type: 'POST',
url: 'URL',
data: { 'Note': note, 'Story': story },
dataType: 'text',
success: function (data) { }
});
Can be accessed in an APIController like so:
public void Update([FromBody]JObject data)
{
var Note = (String)data["Note"];
var Story = (String)data["Story"];
}

If you append json data to query string, and parse it later in web api side. you can parse complex object too. It's useful rather than post json object, espeicaly in some special httpget requirement case.
//javascript file
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);
doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
window.console.log(result);
});
//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
int userID = int.Parse(queryJson.UserID.Value);
string userName = queryJson.UserName.Value;
}
//utility function:
public static dynamic ParseHttpGetJson(string query)
{
if (!string.IsNullOrEmpty(query))
{
try
{
var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
json = System.Web.HttpUtility.UrlDecode(json);
dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);
return queryJson;
}
catch (System.Exception e)
{
throw new ApplicationException("can't deserialize object as wrong string content!", e);
}
}
else
{
return null;
}
}

In .NET Core, the HttpClient sets the transfer-encoding: chunked header by default. This can cause the .NET Web API controller parameters to be null.
To get around this, you'll need to set the ContentLength header explicitly:
var json = JsonConvert.SerializeObject(myObject);
var content = new StringContent(json, Encoding.UTF8, "application/json");
content.Headers.ContentLength = json.Length;
var response = await client.PostAsync("http://my-api.com", content);
SO answer if you already know the transfer-encoding header is the issue: How to disable Chunked Transfer Encoding in ASP.Net C# using HttpClient
Related bug which won't be fixed, which gives some insight into the problem: https://github.com/dotnet/runtime/issues/30283

Related

C# and Ajax - Posting 2 values from JS to C#

I'm using ajax to send an int64 and a string from a month selector to my server-side, but my variable is always null or 0.
JS:
function deleteConta(id) {
var data = $("#monthSelector").val();
var params = {
id: id,
dataAtual: data
};
$.ajax({
type: "POST",
url: '/Contas/ContaView?handler=Delete',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (partialReturn) {
$("#partial").html(partialReturn);
}
});
}
C#:
public PartialViewResult OnPostDelete([FromBody] long id, string dataAtual)
{
contaDTO.Remove(id, contaDTO.Database, contaDTO.ContaCollection);
dataCorrente = DateTime.ParseExact(dataAtual, "yyyy-MM", null).AddMonths(1);
contas = BuscarContasUsuarioMes(User.Identity.Name, dataCorrente);
return Partial("_PartialContas", contas);
}
I already checked with debugger and my variables are ok and filled with value expected (One test was like {id: 50, dataAtual: '2023-01'}
Checked a lot of forums, but Couldn't figure out how to make this thing work.
By declaring the number parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class.
Have you tried to remove it and sending value to the action?
—- UPDATE ——
Try this
function deleteConta(id) {
var data = $("#monthSelector").val();
$.ajax({
type: "POST",
url: '/Contas/ContaView?handler=Delete',
data: { id: id, dataAtual: data },
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (partialReturn) {
$("#partial").html(partialReturn);
}
});
}

Insert json string into mongoDB c# driver v2.4.3

I get a json result from an javascript api query(no problems, valid json) and I would like to insert it into mongoDb.
My json string:
{"data":[{"accessible_wheelchair":true,"address":"181 Washington St","attire":"casual","category_ids":[344],"category_labels":[["Social","Food and Dining","Ice Cream Parlors"]],"country":"us","cuisine":["Ice Cream","Frozen Yogurt","Bagels","Deli","Donuts"],"factual_id":"403b11e4-c383-4305-8ba1-96aa6339eaba","hours":{"sunday":[["11:00","22:00"]],"saturday":[["11:00","22:00"]],"tuesday":[["11:00","22:00"]],"friday":[["11:00","22:00"]],"thursday":[["11:00","22:00"]],"wednesday":[["11:00","22:00"]],"monday":[["11:00","22:00"]]},"hours_display":"Open Daily 11:00 AM-10:00 PM","latitude":42.707169,"locality":"Boxford","longitude":-71.066385,"meal_deliver":false,"name":"Benson Ice Cream","open_24hrs":false,"parking":true,"payment_cashonly":false,"postcode":"01921","price":1,"rating":4.5,"region":"MA","tel":"(978) 352-2911","website":"http://bensonsicecream.com/","wifi":false},{"accessible_wheelchair":true,"address":"256 Georgetown Rd","address_extended":"Unit 5","attire":"casual","category_ids":[363],"category_labels":[["Social","Food and Dining","Restaurants","Pizza"]],"country":"us","cuisine":["Pizza","Cafe","Sandwiches","Subs"],"factual_id":"05e95c81-1125-447b-a500-84e0d380540d","fax":"(314) 423-3377","hours":{"sunday":[["11:00","21:00"]],"saturday":[["11:00","22:00"]],"tuesday":[["11:00","21:00"]],"friday":[["11:00","22:00"]],"thursday":[["11:00","21:00"]],"wednesday":[["11:00","21:00"]],"monday":[["11:00","21:00"]]},"hours_display":"Mon-Thu 11:00 AM-9:00 PM; Fri-Sat 11:00 AM-10:00 PM; Sun 11:00 AM-9:00 PM","latitude":42.697431,"locality":"Boxford","longitude":-70.988191,"meal_cater":true,"meal_deliver":true,"meal_takeout":true,"name":"Boxford House of Pizza","open_24hrs":false,"parking":true,"payment_cashonly":false,"postcode":"01921","price":1,"rating":4.5,"region":"MA","tel":"(978) 887-2212","website":"http://www.bostonrestaurantgroup.com","wifi":false}],"included_rows":2,"total_row_count":2}
I post the json string(arrayString) to a C# controller with ajax.
$.ajax({
url: '/Place/CreateMany',
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify(arrayString),
success: function (valid) {
if (valid) {
alert("success ");
} else {
alert("failure" + arrayString);
}
}
});
The controller errors out with a vague 500 internal server error.
[HttpPost]
public ActionResult CreateMany(string arrayString)
{
JObject jObject = JObject.Parse(arrayString);
JToken placeObj = jObject["data"];
foreach (string data in placeObj)
{
//have a working model defined called PlaceModel
//works with insertOne
var document = BsonSerializer.Deserialize<PlaceModel>(data);
//I am using a working repo(InsertPlace) that uses MongoDB method "insertOne"
//I would like to use a new repo that uses "insertMany"
this._places.InsertPlace(document);
}
return RedirectToAction("List", _places.SelectAll());
}
Not sure what to do to go from json string array of more than one to a single object of my model type (PlaceModel)
This is my first post, so please go easy, but I am open to suggestions.
Veeram was correct. I needed to use BSON serialization not JSON.
[HttpPost]
public void CreateMany(string jsonString)
{
//sets up mongo connection, DB and collection
var Client = new MongoClient();
var DB = Client.GetDatabase("PlacesDb");
var collection = DB.GetCollection<PlaceModel>("PlaceCollection");
if (jsonString != null)
{
IList<PlaceModel> documents = BsonSerializer.Deserialize<IList<PlaceModel>>(jsonString);
collection.InsertMany(documents);
}
}
On the ajax post, I had to add datatype: 'json' and pass my json string as an array jsonString:jsonString with jsonString in [] brackets
self.saveToMongoDB = function (jsonString) {
$.ajax({
url: '/Place/CreateMany',
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify({ jsonString: jsonString }),
success: function (valid) {
if (valid) {
alert("success " + jsonString);
} else {
alert("failure" + jsonString);
}
}
});
};

Getting JSON Object from MVC Controller

What I want is to protect my developer key while making an Ajax call to a cross-domain. Before I would just go straight to the url and plug in my key. Like this
$.ajax({
url: "https://na.api.pvp.net/api/lol/na/v2.3/team/TEAM-ID?api_key=mykey",
type: "GET",
data: {},
success: function (json) {
console.log(json);
console.log(json[teamID].name);
console.log(json[teamID].fullId);
console.log(json[teamID].roster.ownerId);
console.log(json[teamID].tag);
},
error: function (error) {}
});
This would give me the following Object, which I could easily parse out.
However, as mentioned, any person could easily grab my key during this process. So I decided to move this action to my Controller (yes I know there shouldn't be business logic here, but it is more secure and this is a quick process).
So what I am doing now is running my Javascript, which calls the Controller for a Json return.
Javascript
$.ajax({
url: "/Competitive/teamLookUp",
type: "POST",
data: "ID=" + teamID,
success: function (json) {
console.log(json);
},
error: function(error) {
}
});
And my Controller takes that in and attempts to return the JSON.
[HttpPost]
public ActionResult teamLookUp(string ID)
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://na.api.pvp.net/api/lol/na/v2.3/team/" + ID + "?api_key=myKey");
myReq.ContentType = "application/json";
var response = (HttpWebResponse)myReq.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
return Json(new { json = text });
}
However during this processs I return a string that is not a JSON object, thus cannot be parsed by my script.
It returns the entire json as one long string.
At this point I tried to add the following to my Controller.
var json2 = JsonConvert.DeserializeObject(text);
return Json(new { json = json2 });
But all that returned was some empty Object.
I have been trial and error'ing, searching, and guessing for the past 4 hours. I have no idea what to try anymore. I just want my Controller to pass back an Object that can be readable again like this. (Or at least some sort of formatted json object)
$.ajax({
url: "/Competitive/teamLookUp",
type: "POST",
data: "ID=" + teamID,
success: function (json) {
console.log(json);
console.log(json[teamID].name);
console.log(json[teamID].fullId);
console.log(json[teamID].roster.ownerId);
console.log(json[teamID].tag);
},
error: function (error) {}
});
Your method doesn't appear to need to be a POST as it is just getting data rather than modifying it. Therefore you could set it to be a GET instead.
Example
[HttpGet]
public JsonResult teamLookUp(string ID)
{
// Your code
return Json(text, JsonRequestBehavior.AllowGet);
}
Here's an excerpt from your code:
[HttpPost]
public ActionResult teamLookUp(string ID)
{
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("https://na.api.pvp.net/api/lol/na/v2.3/team/" + ID + "?api_key=myKey");
myReq.ContentType = "application/json";
// here's how to set response content type:
Response.ContentType = "application/json"; // that's all
var response = (HttpWebResponse)myReq.GetResponse();
string text;
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
return Json(new { json = text }); // HERE'S THE ERRING LINE
}
Based on the response you received, I could understand that text already contains you desired JSON.
Now replace return Json(new { json = text }); with Json(text); and that should fix it.
To answer your question in the comments, here's how you can read the response data:
$.ajax({
url: "/Competitive/teamLookUp",
type: "POST",
data: "ID=" + teamID,
dataType: "json", // type of data you're expecting from response
success: function (json) {
console.log(json);
console.log(json[teamID].name);
console.log(json[teamID].fullId);
console.log(json[teamID].roster.ownerId);
console.log(json[teamID].tag);
},
error: function (error) {}
});
I think the problem lies where you say return Json(new {json = text;}). That's telling the json serializer to dump all your data into a property in the json obect called 'json', which is what you're seeing in the response.
Try return Json(text) instead.
Ending up using WebClient
[HttpPost]
public ActionResult teamLookUp(string ID)
{
string text = "";
try
{
using (var webClient = new System.Net.WebClient())
{
webClient.Encoding = Encoding.UTF8;
var json2 = webClient.DownloadString("https://na.api.pvp.net/api/lol/na/v2.3/team/" + ID + "?api_key=myKey");
return Json(json2);
}
}
catch (Exception e)
{
text = "error";
}
return Json(new { json = text });
}
And I parsed it like normal,
$.ajax({
url: "/Competitive/teamLookUp",
type: "POST",
data: "ID=" + ID,
dataType: "json",
success: function (resp) {
if (resp["json"] == "error") {
// error reaching server
} else {
// successfully reached server
}
json = JSON && JSON.parse(resp) || $.parseJSON(resp);
var userID = ID;
teamName = json[userID].name;
teamID = json[userID].fullId;
teamCPT = json[userID].roster.ownerId;
teamTag = json[userID].tag;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// error
}
});
I was having the same issue as the original poster: the ReadToEnd() call result escapes special characters and thus doesn't look like JSON to the receiving end, but then I saw a similar question answered here and thought others reading this might find it helpful as well.
To summarize: Deserializing in the Controller which the original poster tried was key, but also as others have pointed out, the return doesn't need the new {} call.
So pieced together:
using (var sr = new StreamReader(endpointResponse.GetResponseStream())) {
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = serializer.DeserializeObject(sr.ReadToEnd());
return Json(jsonObject, JsonRequestBehavior.AllowGet);
}

Post array of strings to web API method

this is my client side ajax call:
var list = ["a", "b", "c", "d"];
var jsonText = { data: list };
$.ajax({
type: "POST",
url: "/api/scheduledItemPriceStatus/updateStatusToDelete",
data: jsonText,
dataType: "json",
traditional: true,
success: function() { alert("it worked!"); },
failure: function() { alert("not working..."); }
});
this is chrome network header:
Request URL:http://localhost:2538/api/scheduledItemPriceStatus/updateStatusToDelete
Request Method:POST
Request Headersview source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:27
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:localhost:2538
Origin:http://localhost:2538
Referer:http://localhost:2538/Pricing/ScheduledItemPrices
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
X-Requested-With:XMLHttpRequest
Form Dataview URL encoded
data:a
data:b
data:c
data:d
this is my webapi controller method:
public HttpResponseMessage UpdateStatusToDelete(string[] data)
result:
when I debug, the data parameter in UpdateStatusToDelete returns {string[0]} instead of data:a
data:b
data:c
data:d
What am I doing wrong? Any help is really appreciated.
For passing simply types, the data to post must take the form of a name value pair with the name portion being an empty string. So you need to make the Ajax call like so:
$.ajax({
type: "POST",
url: "/api/values",
data: { "": list },
dataType: "json",
success: function() { alert("it worked!"); },
failure: function() { alert("not working..."); }
});
Additionally, on your Web API action, annotate it w/ the [FromBody] attribute. Something like:
public void Post([FromBody]string[] values)
That should do the trick.
You should pass the list itself, and not any other object wrapping it.
E.g. pass the following:
var list = ["a", "b", "c", "d"];
in
$.ajax({
type: "POST",
url: "/api/scheduledItemPriceStatus/updateStatusToDelete",
// Pass the list itself
data: list,
dataType: "json",
traditional: true,
success: function() { alert("it worked!"); },
failure: function() { alert("not working..."); }
});
Your method signature on server is correct.
use var jsonText = { data: JSON.stringify(list)}
In the backend, you could use FormDataCollection.GetValues(string key) to return an array of strings for that parameter.
public HttpResponseMessage UpdateStatusToDelete(FormDataCollection formData) {
string[] data = formData.GetValues("data");
...
}
use the method above to send array as suggested by cris in your jquery ajax call.
JSON data is usually in key value pair.
var tmp = [];
tmp.push({
//this is the key name 'a' "a": "your value", //it could be anything here in
//string format.
"b": "b",
"c": "c",
"d": "d"
});
{ data: JSON.stringify(tmp);}
You can also accomplish above by using two dimensional array
Additionally do this in the webapi project.
under the models folder in your web api project create a class file. Possibly class1.cs.
Create 4 properties
public string a {get; set;}
public string b {get; set;}
public string c {get; set;}
public string d {get; set;}
Now do this in your controller
using projectname.models
[HttpPost]
public return-type actionname(List<Class1> obj)
{
//Further logic goes here
}
I am sure this will work.
Setting the dataType won't help you.
This is how I do it :
var SizeSequence = {};
SizeSequence.Id = parseInt(document.querySelector("dd#Sequence_Id").textContent);
SizeSequence.IncludedSizes = [];
var sizes = document.querySelectorAll("table#IncludedElements td#Size_Name");
// skipping the first row (template)
for (var i = 1, l = sizes.length ; i != sizes.length ; SizeSequence.IncludedSizes.push(sizes[i++].textContent));
$.ajax("/api/SizeSequence/" + SizeSequence.Id, {
method: "POST",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(SizeSequence.IncludedSizes),
...
The Server Part
// /api/SizeSequence/5
public async Task<IHttpActionResult> PostSaveSizeSequence(int? Id, List<String> IncludedSizes)
{
if (Id == null || IncludedSizes == null || IncludedSizes.Exists( s => String.IsNullOrWhiteSpace(s)))
return BadRequest();
try
{
await this.Repo.SaveSizeSequenceAsync(Id.Value, IncludedSizes );
return Ok();
}
catch ( Exception exc)
{
return Conflict();
}
}
References
jQuery.ajax()
You can also do this with JSON.stringify, which feels more semantically intuitive than putting things in an object with an empty string key. (I am using Web API 2, not sure if that matters.)
Client code
$.ajax({
type: 'POST', //also works for PUT or DELETE
url: '/api/UserRole',
contentType: "application/json",
data: JSON.stringify(["name1", "name2"])
})
Server Code
[HttpPost]
[Route("api/UserRole")]
public IHttpActionResult AddUsers(string[] usernames)

Passing complex JSON string to 1 parameter webmethod in c# - desearialize into object (json.net)?

I have been happy serializing with javascript objects into JSON using
JSON.stringify
And sending along to my "static" webmethod in c#/asp.net and sure enought it arrives .. I need the correct number of parameters hence if my json object has "startDate","endDate","reserve" then my webmethod needs these as parameters.
"Basically with my order object that i have, i have a number of parameters on this object so i would need to use the same number on the webmethod - this is a bit messy??" - I will explain
I have a rather complex "Order" object in javascript and wish to serialize it using stringify and send it along to my webmethod but i don't want to specify all the parameters is there a way round this?
I was hoping for something like this on my webmethod
public static bool MakeReservation(object order)
Then in my webmethod i only have 1 parameter BUT i can then desearilize this to a true c# object using JSON.NET. I have tried it like this sending the json across but because there is ONLY 1 parameter on my webmethod its failing.
Basically what i am trying to say if i that i want to continue to use my webmethod but i don't want to have to do specify 15 parameters on the webmethod
I want the JSON - String to arrive into my webmethod and then i can decompose it on the server.
Is this possible?
Here is how i am currently sending my JSON to the server (webmethod) using jquery
var jsonData = JSONNew.stringify(orderObject);
$.ajax({
type: "POST",
url: "MyService.aspx/DoReservation",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
success = true;
},
error: function(msg) {
success = false;
},
async: false
});
If you try to submit an object that looks like this:
JSON.stringify({ endDate: new Date(2009, 10, 10), startDate: new Date() });
it will try and map endDate and startDate to corresponding parameters in your webmethod. Since you only want to accept one single method, I suspect you may get away with it by submitting the following:
JSON.stringify({ order: orderObject });
Which it might reasonably try to assign as a value to the 'order' parameter of your webmethod. Failing that, submitting
JSON.stringify({ order: JSON.stringify(orderObject) });
and then deserializing it using JSON.NET should definitely work, but it's uglier, so try the first example first. That's my best shot.
It's possible. I'm not so good at explaining stuff, I'll just show you my example code:
Javascript:
var Order = function(name, orderid, price) {
this.name = name;
this.orderid = orderid;
this.price = price;}
var pagePath = window.location.pathname;
function setOrder() {
var jsOrder = new Order("Smith", 32, 150);
var jsonText = JSON.stringify({ order: jsOrder });
$.ajax({
type: "POST",
url: pagePath + "/SetOrder",
contentType: "application/json; charset=utf-8",
data: jsonText,
dataType: "json",
success: function(response) {
alert("wohoo");
},
error: function(msg) { alert(msg); }
});
}
C# Code behind
public class Order
{
public string name { get; set; }
public int orderid { get; set; }
public int price { get; set; }
}
[WebMethod]
public static void SetOrder(object order)
{
Order ord = GetOrder(order);
Console.WriteLine(ord.name +","+ord.price+","+ord.orderid);
}
public static Order GetOrder(object order)
{
Order ord = new Order();
Dictionary<string,object> tmp = (Dictionary<string,object>) order;
object name = null;
object price = null;
object orderid = null;
tmp.TryGetValue("name", out name);
tmp.TryGetValue("price", out price);
tmp.TryGetValue("orderid", out orderid);
ord.name = name.ToString();
ord.price = (int)price;
ord.orderid = (int) orderid;
return ord;
}
My code isn't that beautiful but I hope you get the meaning of it.
I recently went through this very issue with a complexe JSON object I wanted to deserilize in my controller. The only difference is I was using the .toJSON plugin on the client instead of .stringify.
The easy answer:
public static bool MakeReservation(string orderJSON)
{
var serializer = new JavaScriptSerializer();
var order = serializer.Deserialize<Order>(orderJSON);
}
Now, as a longer term solution we created a custom ActionFilterAttribute to handle these cases. It detects the JSON parameters and handles deserilizing the object and mapping to the action. You may want to look into doing the same.

Categories

Resources