I have trouble sending AJAX post request to controller. The following code works:
var path = $(this).prop("value");
var token = $('[name=__RequestVerificationToken]').val();
var headers = {};
headers["__RequestVerificationToken"] = token;
var ids = $("#ids").val();
var formData = new FormData();
formData.append('ids', ids);
$.ajax({
url: path,
type: "POST",
cache: false,
headers: headers,
data: formData,
async: false,
processData: false,
contentType: false,
success: function (result) {
document.write(result);
document.close();
console.log("YES");
},
error: function () {
alert("Error.");
}
});
Here is the Controller Method:
[AjaxOnly]
[HttpPost]
[ValidateAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult MyMethod(string aString)
The call to the Controller works fine, but as expected aString in Controller-Function parameter is null.
What I actually want to do is not to POST the formData ($("#myForm").serialize();) in the data field of the AJAX post, but an hiddenField:
var aString = $("#ids").val();
So when I put the aString variable in the data field of Ajax call instead of formData the call to my function does not work anymore and I get 500 error.
Anyone can help how to POST this hiddenfield value instead of formData?
MyForm:
#{
ViewBag.Title = "MyForm";
#model MyFormModel
}
#using (Html.BeginForm("MyForm", "MyController", FormMethod.Post, new { id = "MyForm" }))
{
<div class="tab-content" id="tabContent">
content
</div>
#Html.Partial("_MyFormPopup")
Partial:
#using (Html.BeginForm("MyMethod", "MyController", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="modal fade">
content
</div>
#Html.Hidden("ids")
Controller Code:
[AjaxOnly]
[HttpPost]
[ValidateAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult MyMethod(string ids)
{
string[] IdsFunktions = ids.Split(new string[] { ";" },
....
return RedirectToAction("MyForm");
}
So in order for your code to work you need to correctly name your formData variables, here are the two variants:
If you want to have a aString variable on your Controller then your AJAX post code should post like this:
var formData = new FormData();
formData.append('aString', $("#ids").val());
$.ajax({
url: path,
type: "POST",
cache: false,
headers: headers,
data: formData,
async: false,
success: function (result) {
document.write(result);
document.close();
},
error: function () {
alert("Error.");
}
});
Another solution would be in the case you want to post all form fields data by using data: $("#myForm").serialize() you must change the Controller reference variable names and reference each field by its form name, e.g if you have only one hidden field then:
[AjaxOnly]
[HttpPost]
[ValidateAntiForgeryToken]
[OutputCache(NoStore = true, Location = OutputCacheLocation.None)]
public ActionResult MyMethod(string ids, string fieldNameOne, string fieldNameTwo, etc...)
Related
I am trying to get the value passed from the ajax request into one of the method in the controller but IFormFile files is null every time.
Here is my ajax request :
uploadFile: function (field, value)
{
var me = this;
var view = me.getView();
var fileuploadControl = me.lookupReference('ImportFile');
var file = fileuploadControl.fileInputEl.el.dom.files[0];
var param = new FormData();
param.append('files', file);
var ajax = Ext.Ajax.request(
{
url: './../XYController/ImportCSVFile',
data: param,
method: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: { 'accept': '*/*' },
processData: true,
success: function (response, options) {
var result = JSON.parse(response.responseText);
if (mask) {
mask.destroy();
}
Ext.Msg.alert("File Upload Successful");
}
});
},
And this is my Action Controller :
[HttpPost]
[Route("XYController/ImportCSVFile")]
public IActionResult ImportCSVFile(IFormFile files)
{
if(files!=null)
{
//do something
}
}
For file upload , The contenttype needs to be set to false along with the processData option. Otherwise jQuery will not see this as a file upload :
processData: false,
contentType: false,
See code samples from here , that should be same no matter use ExtJS or other Jquery wrapper library .
I have a very specific need to serialize a model in the view and then pass it to a controller action at some point. I can get it to work by doing several hacks but its not pretty.
My test controller action
public ActionResult Index()
{
DefaultOptionValueRound defaultOptionValueRound = new DefaultOptionValueRound()
{
OptionId = 1835,
OptionValueId = 40343
};
TestModel testModel = new TestModel()
{
DefaultOptionValueRound = defaultOptionValueRound
};
return View(testModel);
}
The View
#using Common.Repository.Extensions
#model EngA.SandboxApplication.Controllers.TestModel
#Html.Hidden("DefaultOptionValueRound", Html.Raw(Json.Encode(Model.DefaultOptionValueRound)))
<input type="button" value="submit" onclick="SerializeModelTest.processOptionMag()"/>
<script language="javascript">
SerializeModelTest = {
processOptionMag: function () {
//Testing: This Works
//var defaultOptionValueRound = { OptionId: 1834, OptionValueId: 4034377 }
//var data = JSON.stringify({ defaultOptionValueRound: defaultOptionValueRound });
//This Does Not Work
var defaultOptionValueRound = $("#DefaultOptionValueRound").val();
var data = { defaultOptionValueRound: defaultOptionValueRound }; //Stringify Does not work either
$.ajax({
contentType: 'application/json; charset=utf-8',
type: "Post",
cache: false,
url: '#Url.Action("ProcessOptionMag", "SerializeModelTest")',
data: data,
dataType: "json",
traditional: true,
success: function(data) {
alert(data);
}
});
}
}
</script>
The problem is that the serialized model is returned in a stringify form already.
There must be an elegant way of doing this without me have to do JS string manipulation to make it work.
Thank you for your help
I found out that I can un-stringify my result using JSON.Parse and then repackage it with other parameters for sending to the controller.
var defaultOptionValueRound = $("#DefaultOptionValueRound").val();
var data = JSON.stringify({ defaultOptionValueRound: JSON.parse(defaultOptionValueRound) });
Now everything works.
I need to send data from the client html back to the spring controller.
I have a controller which generates a Json array whichh I sent via ajax to the html side when requested.
That functions well.
The Problem is I need to send the Json array back to another controller for evaluation and changes.
If I post the data and assign an class object of the original class I get the error " Bad request" and it didn't work.
If I assign an object in the controller which consumes the post. That works
but I get an hashmap for which I dont know how to access.
I cant cast it to another class nor access it to work with it.
Since I am new to this can someone give me an advice how to consume the post
on the receiving controller side.
Thanks
Khelvan.
Controller code ist stated below
controller 1 for Get
#RequestMapping("/Person")
#ResponseBody
public ArrayList<Person> ajax_Person_array()
{
ArrayList<Person> Dummy = new ArrayList<Person>();
for ( x=0; x < 5; x++ ){
Dummy.setName("Alfon");
Dummy.setID("5");
Dummy.setStree("Delta");
Dummy.setName("Neutral");
Person.add(Dummy);
}
return Dummy;
}
Controller 2 for post
#RequestMapping(value="/ajax", method=RequestMethod.POST, consumes = "application/json")
//public #ResponseBody String post( #RequestBody Object ajax_Person_array()) {
public #ResponseBody String post( #RequestBody ArrayList<Person> ajax_Person_array()) {
System.out.println("First TEST");
String Success = "OK";
return Success;
}
Html : get ajax
var ajax_data;
$.ajax({
url: "http://localhost:8080/Person",
async: false,
dataType:'json',
cache: false,
success: function (data) {
ajax_data = data;
alert("success ");
},
error:function(){alert("something went wrong ");}
});
}
Html post ajax
$.ajax({
url: "http://localhost:8080/ajax",
type: 'POST',
dataType: 'text',
data: ajax_data,
// data: JSON.stringify(ajax_data),
contentType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
document.write(data);
}
});
#RequestMapping (value="/ajax", method=RequestMethod.POST, consumes = "application/json")
public #ResponseBody JSONObject post( #RequestBody JSONObject person) {
//Pass data to a service to process the JSON
}
For your ajax request, do not set dataType to 'Text'. Set it to JSON
$.ajax({ url: "http://localhost:8080/ajax",
type: 'POST',
dataType: 'json',
data: JSON.stringify(ajax_data),
contentType: 'application/json',
success: function(data) {
alert(data);
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
document.write(data);
}
});
I am trying to call an mvc 3 action method with jquery ajax. please let me note that I am generating a partial view in ajax, and in the generated partial view, I am calling ajax again (it is something like nested ajax calls). here is my code:
the partial view:
#model MYWeb.UI.Models.ClientDetailsViewModel
The javascript in the view:
<script type="text/javascript">
$(document).ready(function () {
$("#savedetails#(i)").click(function () {
var clientNumber = $('#ClientNumber#(i)').val();
var clientName = $('#ClientName#(i)').val();
var client =
{
ClientNumber: clientNumber,
ClientName: clientName
};
alert(JSON.stringify(client));
$.ajax({
url: '/Home/ClientUpdate',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(client),
beforeSend: function () {
$("#loader#(i)_details").fadeIn('fast');
},
complete: function () {
$("#loader#(i)_details").fadeOut('fast');
},
success: function () {
$("#loader#(i)_details").fadeOut('fast');
if ($("#ModelFirstError").val())
showModelMessageError;
else
showUpdateMessageSuccess();
},
error: function () {
$("#loader#(i)_details").fadeOut('fast');
showUpdateMessageError();
},
async: true,
processData: false
});
});
});
the Model object:
public class ClientDetailsViewModel
{
[Display(ResourceType = typeof(adm), Name = "ClientNumber")]
public int ClientNumber { get; set; }
[Required(AllowEmptyStrings = false, ErrorMessageResourceName = "RequiredClientName", ErrorMessageResourceType = typeof(adm))]
[Display(ResourceType = typeof(adm), Name = "ClientName")]
public string ClientName { get; set; }
more fields...
}
the action method:
[Authorize]
[HttpPost]
public ActionResult ClientUpdate(ClientDetailsViewModel client)
{}
this attempt to update always returns the ajax error. what am I doing wrong?
Edit:
I noticed that when I remove the parameter to the action method, it does get called.
But how can I pass the model this way?
[Authorize]
[HttpPost]
public ActionResult ClientUpdate()
{}
I have a Spring MVC web application and I have the following web service.
#RequestMapping(value = "/newBill", method = RequestMethod.POST)
public #ResponseBody ModelMap acceptNewBill(#ModelAttribute ("Bill") Bill newBill ){
Bill bill = new Bill();
bill.setTableName(newBill.getTableName());
bill.setRoom(newBill.getRoom());
bill.setCovers(newBill.getCovers());
ModelMap model = new ModelMap();
model.put("status", true);
return model;
}
The following Script performs the front end functions.
$('.done').click(function(){
var jsonObject = createJSON(".newBill");
jQuery.ajax({
url: "/newBill",
type: "POST",
data: {bill: JSON.stringify(jsonObject) },
dataType: "json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});
});
function createJSON(elementToConvert) {
jsonObj = [];
$( elementToConvert + " input").each(function() {
var id = $(this).attr("class");
var email = $(this).val();
item = {}
item [id] = email;
jsonObj.push(item);
});
return jsonObj;
}
The above createJSON function go through a provided html element and puts the values into an object! The click function performs the POST and the Post contains the following data.
bill [{"tableName":"326432"},{"room":"3462346"},{"covers":"3426234"}]
Now when I debug and check the service, the data which goes from the front end doesn't get mapped in the parameter. I checked whether the variable names are the same as the POST. They are the same! but the values doesn't get mapped! Can any one please help me with this issue.
Update :
I changed the service method to GET and passed a value as a URL variable. Then it got mapped in the service param. The problem is in the POST.
Instead of using #ModelAttribute in your controller use #RequestBody:
public #ResponseBody ModelMap acceptNewBill(#RequestBody Bill newBill) {
On the ajax call, set the content type to application/json and stringify the whole object instead of just the array:
jQuery.ajax({
url: "/newBill",
type: "POST",
data: JSON.stringify({bill: jsonObject}),
dataType: "application/json",
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(result) {
alert('sadgsd');
}
});