I have this javascript code:
var formData = new FormData($('#formSlip').get(0));
formData.append('myList', JSON.stringify(tests));
Where tests is a list of objects. I'm sending an ajax post request to my controller and within that request I'm sending a file and a list of objects.
$.ajax({
url: url,
type: 'post',
data: formData,
processData: false,
contentType: false,
cache: false,
success://some code
})
I've took a look into my Request Payload using DevTools in Chrome, and it looks like this:
Content-Disposition: form-data; name="firstPdf"; filename="blank.pdf"
Content-Type: application/pdf
Content-Disposition: form-data; name="myList"
[{"key":"Section1","listTitles":["aaaa","aa","aa","a"]},
{"key":"Section2","listTitles":["bb","b","bb","b"]}]
I'm retrieving the file okay in my controller action, but for some reason the list is always empty, this is my controller action:
[HttpPost]
public ActionResult LS10(HttpPostedFileBase firstPdf, List<PdfPieceVM> myList)
{
var t = firstPdf.InputStream;
byte[] pdfByte = new byte[firstPdf.ContentLength];
return File(pdfByte, "application/pdf", firstPdf.FileName);
}
I've created a ViewModel just to get that list:
public class PdfPieceVM
{
public string key { get; set; }
public List<string> listTitles { get; set; }
}
When I debug my code the myList parameter is always empty, but I'm receiving the file, what do I need to do to correct this?
Reading #Alex Menconi referenced post, I changed the controller action to retrieve a string and then deserialize it to the type that I wanted:
[HttpPost]
public ActionResult LS10(HttpPostedFileBase firstPdf, string myList)
{
List<PdfPieceVM> pdfPieces = new
JavaScriptSerializer().Deserialize<List<PdfPieceVM>>(myList);
}
Related
So I am trying to build a travel-based site where I take some values from the UI and am trying to bind it to an object, and then hit an Http post to a controller, which will then take care of the DB part of the JOB. The problem is the controller will be receiving the post data as a complex object. So my present question is actually multifold.
How do I construct an instance and assign values for such a complex object in my client(AngularJS)code?
Is there any way razor can help us by fetching the object.
Once I have the finished, object if I stringify the JSON will the controller be able to accept that version.
I will be giving some code for reference.
ModelClass:
public class SearchCriteria
{
public Routes Routes { get; set; }
public int JType { get; set; }
public PaxInfo PaxInfo { get; set; }
public string SearchFingerPrintID { get; set; }
}
in the above class Routes is a complex type that needs to be addressed.
Razor Code to import the Model Object
#{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var SampleReqObj = serializer.Serialize(Model.MyRequest);
}
Some Angularjs code.
$scope.ButtonClick = function () {
var ReqObjFinal = JSON.parse(SampleReqObj);
var post = $http({
method: "POST",
url: "/Main/DemoFormDataSubmit",
dataType: 'json',
data: JSON.stringify(ReqObjFinal),
headers: { "Content-Type": "application/json" }
});
post.success(function () {
$window.alert("Successful Call");
});
post.error(function () {
$window.alert("Not working bro");
});
}
Field that i want to fetch from my UI.
<input type="text" name="Departure" ng-click="DeptLoadList()"
ng-model="Departure" id="Departure" ng-keydown="completeDept(Departure)"
class="form-control" />
I am a beginner for angular-js so thanks in advance for the help!!!
You can create a ViewModel. And use to it your view page head
#Model.YourViewModel
and use page input name ex :
<form action="post" action="YourController/Save">
<input name="YourViewModel.PropName" type="text" value="#YourViewModel.PropName" />
</form>
and you can post to controller ex:
[HttpPost]
function void Save(YourViewModel data){
string value=data.YourProperty;
}
You can create a structure;
public class YourViewModel{
...
public string DataJson{get;set;}
}
and
var pageData=Json.parse(#Model.DataJson);
pageData.YourProp="Your value";
$http({ method: "POST", url: "/YourController/Save", dataType: 'json', data:
pageData, .. })
that object goes to your controller
I was trying to figure out how I get the body of the JSON object, that I was sending with the listed AJAX POST request.
While debugging the UploadJSON method gets called but is having a jsoninput with null content.
//ASP.NET Core
[HttpPost]
public IActionResult UploadJSON([FromBody] IFormCollection jsoninput)
{
var inputBody = jsoninput;
// Writing JSON object content into a file....
return RedirectToAction("Index");
}
//javascript
function uploadJSON(plistArrayForJSON) {
var sendobj = JSON.stringify({ plistArrayForJSON });
$.ajax({
url: 'https://localhost:5001/home/uploadjson',
type: 'POST',
data: sendobj,
contentType: "application/json",
});
}
The JSON you send is not deserializable as IFormCollection.
//ASP.NET Core
[HttpPost]
public IActionResult UploadJSON([FromBody] IList<PlayList> jsoninput)
{
var inputBody = jsoninput;
// Writing JSON object content into a file....
return RedirectToAction("Index");
}
I am currently trying to call an ajax request from a JavaScript onchange handler to call a Spring MVC controller. I believe the way I am currently calling the URL in my view is wrong since I get an 404 error on the browser when the event is triggered and call for url. Can anyone shine some light if I have everything setup correctly?
Here is my code:
#Controller
public class DataTableController
{
#RequestMapping(value = "/table", method = RequestMethod.GET)
public String home(Model model) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> gpnList = new ArrayList<GPN>();
gpnList.add("GPN-1"); gpnList.add("GPN-2"); gpnList.add("GPN-3");
model.addAttribute("gpnList", mapper.writeValueAsString(gpnList));
return "index"; //name of my view
}
#RequestMapping(value = "/getsector", method = RequestMethod.POST)
public #ResponseBody String getSector(#RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> sectors = new ArrayList<String>();
sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog");
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(sectors);
}
}
Jquery Code:
$(document).ready(function()
{
document.getElementById("markets").onchange = function()
{
var market = $("select[id='markets'").find('option:selected').text();
var filters = { "market" : market }
filters = JSON.stringify(filters);
$.ajax({
url: "/getsector",
type: "POST",
dataType : 'json',
contentType : "application/json",
data: JSON.stringify(filters),
success: function(response)
{
console.log("sucess!");
},
error: function(e){
console.log("ERROR: ", e);
}
});
}
});
The main thing I want to achieve is being able to call my controllers via ajax calls. Any other tips on Spring Controller Mapping and conventions will be appreciated.
If your a requesting information you should use GET requests, not POST.
You are mixing #RequestParam with a json payload. If you want to receive your filter as a request param it has to go at the url, not as a json payload, using something like:
$(document).ready(function()
{
document.getElementById("markets").onchange = function()
{
var market = $("select[id='markets'").find('option:selected').text();
$.ajax({
url: "/getsector?market="+market,
type: "GET",
success: function(response)
{
console.log("sucess!");
},
error: function(e){
console.log("ERROR: ", e);
}
});
}
});
#RequestMapping(value = "/getsector", method = RequestMethod.GET)
public #ResponseBody String getSector(#RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException
{
.... your logic.
}
On the other hand, if you really want to use POST requests with a json payload, you need to use #RequestBody at the controller and bind the json object to a bean with the same properties.
#RequestMapping(value = "/getsector", method = RequestMethod.POST)
public #ResponseBody String getSector(#RequestBody Market market) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> sectors = new ArrayList<String>();
sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog");
return sectors;
}
public class Market
{
String market;
//getter and setter...
}
Bear in mind your javascript is wrong as well, you are using JSON.stringify twice.
If you use #ResponseBody and spring is configured fine it will make the serialisation for you when returning the response, so you do not have to do it manually.
This code has not been tested, it is just for you to get an idea.
Whenever I send 'GET' with JSON.stringify() using AJAX, model value is always accept null;
Why it can only bind 'POST'?
If it is possible, can I use 'GET' and still bind data to model?
Edit: adding Code Example
JS:
$.ajax({
var modelsend = {
itemname: 'shoe',
itemcolor: 'red',
itemsize: '31',
itemvariety: 'SR-31',
}
type: "POST",
url: "#Url.Action("ShowData", "Controller")",
data: JSON.stringify(modelsend),
dataType: "json",
contentType: "application/json",
success: function (data) {
//do something with data
},
error: function (jqXHR, textStatus, errorThrown) {
//show error
}
});
Model:
public class shoemodel
{
public string itemname { get; set; }
public string itemcolor { get; set; }
public string itemsize { get; set; }
public string itemvariety { get; set; }
}
Controller:
public ActionResult ShowData(shoemodel get)
{
List<DataGrid> fetch = func.getdata(get);
return Json(fetch);
}
Perhaps you are forgetting that GET is used for viewing something, without changing it, while POST is used for changing something. And Get can be used to change something only when you use Querystring. Post on the other hand sends form data directly.
HTTP 'GET' method doesn't support a body in the request. The way to send parameters via 'GET' is using the application/x-www-form-urlencoded format appending them in the URL like this.
http://example.com/?key1=value1&key2=value2
I have two forms, consider Form1 and Form2, both are MVC forms only. These forms using two different view models as shown below :
public class Form1ViewModel
{
//some public properties
public string QueryString { get; set; }
}
public class Form2ViewModel
{
//some public properties
public string PreviousQueryString { get; set; }
}
In the controller Post Action I'm writing like this :
[HttpPost]
public ActionResult ProcessForm1(Form1ViewModel form1Obj)
{
//some logic goes here
//I'm preparing Querystring from form1 data and appending to Form2 model like
Form2ViewModel form2Obj=new Form2ViewModel();
form2Obj.PreviousQueryString = form1Obj.QueryString;
return View("Form2",form2Obj) ;
}
And in Form1, I'm submitting through Jquery Ajax as
frm.submit(function(ev) {
var formData = frm.serialize();
$.ajax({
type: "POST",
url: 'ControllerName/ProcessForm1',
data: formData,
success: function(response) {
//Here i need to read the PreviousQueryString and need to push to window.history.pushState()
}
error: function() {}
});
});
In the Ajax success, I need to read the PreviousQueryString from the response.
I knew how to do it client side(using pure JS) but it's my requirement.
How can I do it?
Try this
[HttpPost]
public string ProcessForm1(Form1ViewModel form1Obj)
{
JavaScriptSerializer js = new JavaScriptSerializer();
Form2ViewModel form2Obj=new Form2ViewModel();
form2Obj.PreviousQueryString = form1Obj.QueryString;
return js.Serialize(form2Obj);
}
success: function(response) {
var objResponse = $.parseJSON(response);
if (objResponse.PreviousQueryString != "") {
alert(objResponse.PreviousQueryString);
}
}