I have seen a lot of posts that seem to somewhat address my situation but they all leave me a bit confused.
I have an object that I am POSTing to my Controller. I have the post coming to my controller okay by doing this:
$('#fileSubmit').click(function () {
var filesObj = [];
$('#fileList .files .fileName').each(function () {
var name = $(this).text();
filesObj.push({ 'name': name });
});
$.ajax({
type: "POST",
url: "/FileUpload/ImportCommit",
data: filesObj,
dataType: "json"
});
});
I want to then take that JSON object and put it into a list in my controller. So far here is what i have, but I have not done a lot of coding in C# and don't know what to do next.
[HttpPost]
public ActionResult ImportCommit(List<string> filenames)
{
}
I know my controller method's code is blank, but am not sure what to do next. Any help would be much appreciated. Thanks!
The post data you send via the data field of the ajax method needs to be name value pairs. Asp.Net will map them in the Request Params collection via their name. E.g. if you post an object like this,
{
fileNames: JSON.stringify(arFileNames)
};
It can then be accessed server side via,
string json = HttpContext.Current.Request.Params["fileNames"];
If your json looks something like this,
"{"filenames":["somefile","somefile2","somefile3"]}"
You could use newtonsoft JSON (JSON.Net) to convert it to a list of strings by creatong a class to represent it, like this,
public class JsonResultFileNames
{
[Newtonsoft.Json.JsonProperty(PropertyName = "filenames")]
public string[] FileNames { get; set; }
}
Then convert the json to JsonResultFileNames with,
JsonResultFileNames jsonResult = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonResultFileNames>(jsonStringHere);
Then you have a c# object representing your json data. Also you can get way more complex with this, but the important thing to note with JSON.Net, is it quite literally deserializes into a c# representation. E.g. if you want to deserialize straight to a string array, then there should only be an array of strings in your json (no object/field names etc).
E.g. where I work we have an api that returns results like this,
{
status: {
success: true;
},
customerdata {
id: {some-guid},
name: Some Customer Name
}
}
The problem with that, is my C# class needs to be composed of nested classes, e.g. I need a class to represent status and a class to represent customerdata. Things can get weird naming wise when doing that, I ended up with things like CustomerResponse, CustomerResponseStatus, CustomerResponseData, where CustomerResponseStatus and CustomerResponseData are exposed in CustomerRespnose, and I deserialize the json to the CustomerResponse type.
If your json is just an array of strings, you should be able to use string[] for the type passed into JsonConvert.Deserialize, which would not require you to make response classes to hold the data.
The trick was to modify my AJAX to POST like this:
$.ajax({
type: "POST",
url: "/dat/Controller",
data: JSON.stringify(filesObj),
contentType: "application/json",
traditional: true,
success: function (result) {
console.log("Success: " + result);
},
error: function (result) {
console.log("Error: " + result);
}
});
Changing dataType to contentType and adding traditional: true seemed to do the trick for me. The reason for this (I believe) is because the actual data that I was posting is technically not JSON. I added the traditional: true just to be on the safe side.
Related
My app is made in ASP.NET MVC 5. User can use search form which is displaying filtered data. Now I want to add button which will export displayed data.
To do this I am sending Search object to view and save it in html. Now When clicking export button I want to pass this object to controller, get data from database using this Search object and save results as text.
The thing is I cant bind json to c# object. Thats my view:
<div id="originalForm" style="visibility:hidden">
#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model))
</div>
This is my ajax code:
function exportRaportToCsv() {
var $formData = $('#originalForm').text();
var allIds = getCheckedIds();
var dataToSend = JSON.stringify({
ids: allIds,
search: $formData
});
$.ajax({
type: "POST",
url: '#Url.Action("ExportToCsv", "BankCosts")',
data: dataToSend,
contentType: "application/json; charset=utf-8",
success: function (datar) {
window.location = '/BankCosts/Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
},
error: function (xhr) {
},
});
}
And this is my controller:
[HttpPost]
public ActionResult ExportToCsv(string[] ids, Search search)
{
// search is null here
}
When I spy sending data with Fiddler I can see, that I am passing this:
{"ids":[],"search":"\n {\"ID\":0,\"DateFrom\":\"2018-06-23T00:00:00\",\"DateTo\":\"2018-06-25T00:00:00\",\"hasUnrecognizedStatus\":false,\"skippedSearchResults\":0,\"paginationLimit\":100}\n"}
I think it is worth to mention, that ids is properly passed. If it contains data, that data is passed. I think the problem is that I have \ in my json. How can I remove this? Is there something wrong with my ajax?
When I use console.log to print $formData I can see that \ characters are gone and it looks better:
{"ID":0,"DateFrom":"2018-06-23T00:00:00","DateTo":"2018-06-25T00:00:00","hasUnrecognizedStatus":false,"skippedSearchResults":0,"paginationLimit":100}
[HttpPost]
public ActionResult ExportToCsv(string[] ids,[FromBody]Search search)
{
}
Try adding FromBody if your Search model is ok it should work.
based on your comments, I think that search object already stringified, so you don't need to stringify it.
just make your json like this
var dataToSend = {
"ids": allIds,
"search": $formData
};
Use JSON.parse() to transforms JSON string to a JavaScript object. Your $('#originalForm').text() is a JSON string actually.
var $formData = JSON.parse($('#originalForm').text());
var allIds = getCheckedIds();
var dataToSend = JSON.stringify({
ids: allIds,
search: $formData
});
In your case, $formData is a string (JSON string actually). So JSON.stringify() again trying to convert to JSON string which is already a JSON string that's causing unnecessary '/' character in form data that you are posting.
Make sure to set the content type to 'application/json' in ajax call properties Otherwise MVC model binder will not be able to map and fill .NET model from JSON posted data.
contentType: "application/json; charset=utf-8",
Since you are using
JSON.stringify
the search value posted in string format not object
Search
so
Try replace your controller with this
[HttpPost]
public ActionResult ExportToCsv(string[] ids, string search)
{
//then deserialize search json like
Search objSearch = JsonConvert.DeserializeObject<Search>(search);
}
or
[HttpPost]
public ActionResult ExportToCsv(string[] ids, JObject search)
{
//then deserialize search json like
Search objSearch = JsonConvert.DeserializeObject<Search >
(dataModel["search"].ToString());
}
View
$.ajax({
type: "POST",
url: '#Url.Action("ExportToCsv", "BankCosts")',
data:{ids= allIds.toString(),search:JSON.stringify($formData)}
contentType: "application/json; charset=utf-8",
success: function (datar) {
window.location = '/BankCosts/Download?fileGuid=' + response.FileGuid
+ '&filename=' + response.FileName;
},
error: function (xhr) {
},
});
NOTE Please see the update at the bottom.
I'm picking up maintenance on an existing (working) application.
The application receives data into a class via a post to a Web API controller action.
However when I try to test this by posting it some data it just gives an empty object.
I assumed that my Json must be wrong so I tried sending the Json string as text and deserializing manually, and this works fine, returning the populated object I would expect to see.
I've searched online and seen various suggestions about adding attributes to the parameters but this doesn't do it for me.
The code looks pretty much as follows:
[HttpPost]
[AllowBasicAuthentication]
public async Task<MyResponse> ProcessData(
[FromUri]string key,
[FromUri]string name,
[FromUri]string value1,
[FromBody] DataClass value // this is never populated
)
{
// the following returns the data as expected
var test = new JavaScriptSerializer().Deserialize<DataClass>(value1);
...
}
The jQuery I'm using to test this is as follows:
$('#post').click(function () {
var key = $('#key').val();
var name = $('#name').val();
var value1 = $('#value').text();
var value = JSON.parse(value1);
var url = '/api/ProcessData/?key=' + key
+ '&name=' + name
+ '&value1=' + value1
/* with this post value appears in action as an instantiated but empty object */
$.post(url, { value: value })
.success(function (r) {
...
})
.fail(function (r) {
...
})
/* also tried the following, but value appears as null object
$.ajax({
url: url,
type: 'POST',
cache: false,
contentType: "application/json",
data: value,
success: function (r) {
alert(r);
}
});
*/
});
[EDIT]
Just to clarify, I added the value1 string parameter to test that the Json can be deserialized correctly, which it can, so the Json is ok and the class is ok.
UPDATE
This works when called from Postman so the error must be in the jQuery.
Can anyone show the correct way to do this?
Thanks
[/EDIT]
I'm trying to post some JSON to a web service. The web-service is executed but there's no data available.
The jQuery looks like this :
var json = {"Results": results};
var jsonArray=JSON.stringify(json);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: jsonArray ,
dataType: "json",
success: function (data) { TCG.QUE.processSaveButtonSucceeded(data); },
error: function (data) { TCG.QUE.processSaveButtonFailed(data); }
});
And the webservice implemented in a controller looks like this :
public HttpResponseMessage Post([FromBody]string value)
{
object o1 = Request.Content;
HttpResponseMessage r = new HttpResponseMessage(HttpStatusCode.OK);
return r;
}
If I take out the [FromBody] directive then I get a 404. If I leave it in the code is executed but the value of the value argument is null.
I thought the [FromBody] directive meant the data was contained in the Request object but if it is I can't find it .
Would appreciate any suggestions so that I can access the JSON from the client within the Post method.
UPDATE:
I just re-read this : http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api which made me wonder whether the name I was giving the JSON blog client side should correspond to the name of the argument on which the [FromBody] is applied so I changed the name of the argument from value to Results but still the value within the Post method is null.
RESOLUTION
After reading the blog post referred to by Prashanth Thurairatnam I changed my method to be like this and it works :
public HttpResponseMessage Post([FromBody]JToken jsonbody)
{
// Process the jsonbody
return new HttpResponseMessage(HttpStatusCode.Created);
}
.
Not sure what you are passing into results. Ran into this blog. You may want to give it a go. The blog talks on passing the data as JSON object/ array (you may want to try without JSON.stringify)
There is quite a lot of helpful information on MVC model binding.
My problem stems from the fact that I am trying to avoid creating strongly typed data in my MVC application as it mostly needs to act as a data router.
Basically, I have a set of fields on a page, with a class 'input', that I can gather with jQuery('.input'), iterate over and stuff into a javascript object. I then send this to my ASP.NET MVC controller:
var inputData = my_serialize( $('input');
$.ajax({
type:'POST',
url: '/acme/Ajax/CaptureInput',
dataType: "json",
data: { inputData: JSON.stringify(inputData) },
success: Page_Response_RegisterAndDeposit,
error: Page_AjaxError
});
On the C# side, I have
public JsonResult CaptureInput(string inputDataAsJsonString)
{
JavaScriptSerializer JSON = new JavaScriptSerializer();
object inputData = JSON.DeserializeObject(inputDataAsJsonString);
This seems like a wasteful level of indirection, I'd prefer to pass the data as contentType:application/json and have CaptureInput accept an object or IDictionary or even a dynamic.
You could use the serializeArray method. Let's suppose that you have a form containing the input elements which could be of any type and you want to invoke the following controller action:
public ActionResult CaptureInput(Dictionary<string, string> values)
{
...
}
here's how you could proceed:
<script type="text/javascript">
var values = $('form').serializeArray();
var data = {};
$.each(values, function (index, value) {
data['[' + index + '].key'] = value.name;
data['[' + index + '].value'] = value.value;
});
$.ajax({
url: '#Url.Action("CaptureInput")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (result) {
alert('success');
}
});
</script>
Not exactly what you're after but maybe the resolution of this issue would give you a partial workaround, by allowing you to bind to a simple wrapper object with an embedded Dictionary. It might even allow binding direct to a Dictionary. Not sure...
You might also need to explicitly set the json ContentType header in your $.ajax call
"JSON model binding for IDictionary<> in ASP.NET MVC/WebAPI"
I went through dozens of answers to figure out the trick to posting data from $.ajax to a parameter in MVC 2's Controller. Here's as far as I got:
BTW this works if you use a GET, but fails as a POST. How would I fix it?
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Home/Get",
data: {value:'9/14/2010 12:00:00 AM'},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.value);
}
});
});
And this is my MVC 2 Controller:
public class strange
{
public string value { get; set; }
}
public JsonResult Get(strange o)
{
var b = new strange { value = "return" };
return Json(b, JsonRequestBehavior.AllowGet);
}
Upon POST, o's "value" is null. Changing POST to GET, o's "value" is "9/14/2010 12:00:00 AM".
How do I get the POST to work with $.ajax?
Did anyone ever post a guide to getting JSON working with MVC2 data validation when returning JSON from the client? I know they had that in their MVC 2 futures a while ago.
The data which you send to the ASP.NET MVC Controller should not be JSON encoded. So you should just remove the line
contentType: "application/json; charset=utf-8",
from the $.ajax request and your program will work.
You need to pass JSON to the controller, and it's looking for a strange object, all you're currently passing is a string called value, instead your data should look like this:
{ strange: { value:'9/14/2010 12:00:00 AM'} }
Notice how strange is not an object with the value property the server is looking for. But, it'll expect this as a string, so just use JSON.stringify() (use JSON2 if needed for other browsers, e.g. < IE8):
data: JSON.stringify({ strange: { value:'9/14/2010 12:00:00 AM'} }),