I read many articles describing this and I tried to use the same mechanism but still it does not work for me.
So, I want to send the object from javascript to my controller.Here is the snippet I tried but error 400(Bad request).
My bean is as follow : (StudentAnswers.java)
public class StudentAnswers {
private Integer testId;
private Integer studentId;
private String[] questionIds;
private String[] answerIds;
..
//all get and set method to access this
}
My javascript file having ajax call is :
function submitTest()
{
var test_id = 1;
var student_id = 1;
var q = [];
q[0] = "question 1";
q[1] = "question 2";
var a = [];
a[0] = "answer 1";
a[1] = "answer 2";
var studentAnswers = {
"testId": test_id,
"studentId": student_id,
"questionIds": q,
"answerIds" : a
};
$.ajax({
type : "POST",
url : "submitTest",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data : studentAnswers,
success : function(response) {
alert('test submitted');
},
error : function(e) {
alert('Error: ' + e);
}
});
Finally, my controller function is :
#RequestMapping(value={"submitTest"},method = RequestMethod.POST)
public ModelAndView submitTest(#RequestBody StudentAnswers studentAnswers)
{
...
return new ModelAndView("student/testBegin");
}
Try to stringify post data like this:
data : JSON.stringify(studentAnswers)
var studentAnswers = new Object();
studentAnswers.testId = "11";
studentAnswers.studentId = "12345";
studentAnswers.questionIds = "secret";
studentAnswers.answerIds ="111";
$.ajax({
url: urlSelected,
type: "POST",
dataType: "json",
data: JSON.stringify(studentAnswers),
contentType: "application/json",
mimeType: "application/json",
success: function (result) {
if (result.success) {
alert(result.message);
} else {
alert(result.message)
}
},
error:function(error) {
alert(error.message);
}
});
Thank you guys for the help.
I tried using JSON.stringify to send the data from AJAX to Controller and it did not work.
JSON.stringify(studentAnswers)
However, when I took a look at the data that I am sending and compare with the type of data expected, I found out that there was a type mismatch.
So, I changed my javascript Object to be identical to my bean. So, following is my object and bean which works fine.
JavaScript Object :
var studentAnswers = new Object();
studentAnswers.testId = 1;
studentAnswers.studentId = 1;
studentAnswers.questionIds = new Array();
studentAnswers.questionIds[0] = "12345";
studentAnswers.answerIds =new Array();
studentAnswers.answerIds[0] = "12345";
Bean :
public class StudentAnswers {
private Integer testId;
private Integer studentId;
private String[] questionIds;
private String[] answerIds;
..
//all get and set method to access this
}
Final AJAX call looks like this :
$.ajax({
type : "POST",
url : "submitTest",
dataType: "json",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data : JSON.stringify(studentAnswers),
success : function(response) {
alert('test submitted');
},
error : function(e) {
alert(e.message);
}
});
Controller Function:
#RequestMapping(value={"submitTest"},method = RequestMethod.POST)
public ModelAndView submitTest(#RequestBody StudentAnswers studentAnswers)
{
System.out.println(studentAnswers.toString());
return new ModelAndView("student/testBegin");
}
Related
the result of content type : "application/x-www-form-urlencoded" stored in Request.Form in Asp MVC.
but for "application/json" i cant find the store location
here is the code that i use:
ajax part
// reading form data
var form = $("form")[0];
var formData = new FormData(form);
var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
var data = JSON.stringify(object);
// ajax part
// POST application/json; charset=utf-8
$.ajax({
type: "POST",
url: "#Url.Action("FormSubmit","Home")",
data: data,
dataType: "json",
async: true,
contentType: "application/json",
processData: true,
success: function(result) { },
error: function(result) { }
});
Controller Part
[HttpPost]
public ActionResult FormSubmit(string input1, string input2)
{
var httpContext= HttpContext;
var response = Response;
var request = Request;
throw new NotImplementedException();
}
You can use controller like this:
[HttpPost]
public ActionResult SomeAction(string data)
{
List<YOUR_MODEL_CLASS> payloadObj = Newtonsoft.Json.JsonConvert.DeserializeObject<List<YOUR_MODEL_CLASS>>(data)(modelData);
// process your data
}
Found the answer
i just need to read post Payload
here is the code
[HttpPost]
public ActionResult FormSubmit()
{
Request.InputStream.Position = 0;
var reqMemStream = new MemoryStream(HttpContext.Request.BinaryRead(HttpContext.Request.ContentLength));
string reqString = Encoding.ASCII.GetString(reqMemStream.ToArray());
throw new NotImplementedException();
}
I am calling a javascript function on button click using onclientclick with below function.
function addValues() {
debugger;
var arrValue = [];
var hdnValue = document.getElementById("hdn").value;
var strValue = hdnValue.split(',');
for (var i = 0; i < strValue.length; i++) {
var ddlValue = document.getElementById(strValue[i]).value;
arrValue.push(ddlValue);
}
}
arrValue array will have all the required values and how can I move this array values to server side for further process.
Update 1:
HTML:
function addValues() {
debugger;
var arrddlValue = [];
var hdnddlValue = document.getElementById("hdnDDL").value;
var strddlValue = hdnddlValue.split(',');
for (var i = 0; i < strddlValue.length; i++) {
var ddlValue = document.getElementById(strddlValue[i]).value;
arrddlValue.push(ddlValue);
}
}
$.ajax({
url: '',
data: { ddlArray: arrddlValue },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (data) {
},
error: function (x, e) {
}
});
Code:
protected void btnSort_Click(object sender, EventArgs e)
{
try
{
if (Request["ddlArray[]"] != null)
{
string[] arrValues = Array.ConvertAll(Request["ddlArray[]"].ToString().Split(','), s => (s));
}
}
}
If your framework is ASP.Net you can pass it by $.ajax, I am passing array like:
$.ajax({
url: '',
data: { AbArray: arrValue },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
},
error: function (x, e) {
}
});
and get it in Back-end like:
if (request["AbArray[]"] != null)
{
int[] arrValues = Array.ConvertAll(request["AbArray[]"].ToString().Split(','), s => int.Parse(s));
}
suppose array is int.
the above sample is using Generic-Handler.
if you want to use webmethod do something like:
[WebMethod(EnableSession = true)]
public static void PassArray(List<int> arr)
{
}
and Ajax would be like:
function addValues() {
debugger;
var arrddlValue = [];
var hdnddlValue = document.getElementById("hdnDDL").value;
var strddlValue = hdnddlValue.split(',');
for (var i = 0; i < strddlValue.length; i++) {
var ddlValue = document.getElementById(strddlValue[i]).value;
arrddlValue.push(ddlValue);
}
var jsonVal = JSON.stringify({ arr: arrValue });
$.ajax({
url: 'YourPage.aspx/PassArray',
data: jsonVal,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {
},
error: function (x, e) {
}
});
}
Change Ajax Url as your PassArray address which mean YourPage.aspx should be change to page name which have PassArray in it's code-behind.
For more info Read This.
If you are using Asp.net WebForm Application,
Approach 1 : you can store your array value in a hidden input control and retrieve the saved data in your c# coding.
Approach 2 : define web method in your server side c# code and pass this javascript array value as ajax call.
link for Approach 1 : https://www.aspsnippets.com/Articles/Pass-JavaScript-variable-value-to-Server-Side-Code-Behind-in-ASPNet-using-C-and-VBNet.aspx
link for Approach 2 : https://www.aspsnippets.com/Articles/Send-and-receive-JavaScript-Array-to-Web-Service-Web-Method-using-ASP.Net-AJAX.aspx
I would "stringify" the array by imploding it with a special char unlikely to appear in my values (for example: §), and then with the help of jQuery.ajax() function, I will send it to the backend (ASP.NET MVC) action method:
$.ajax({
url : 'http://a-domain.com/MyController/MyAction',
type : 'POST'
data : 'data=' + myStringifiedArray;
});
My backend would be something like this (in MyController class):
[HttpPost]
public ActionResult MyAction(string data)
{
string[] arrValue = data.Split('§');
...
}
UPDATE
For ASP.NET forms, the ajax request would be:
$.ajax({
url : 'http://a-domain.com/MyPage.aspx/MyMethod',
type : 'POST'
data : 'data=' + myStringifiedArray;
});
And the backend would be something like this:
[System.Web.Services.WebMethod]
public static void MyMethod(string data)
{
string[] arrValue = data.Split('§');
...
}
You will find a more precise explanation here: https://www.aspsnippets.com/Articles/Call-ASPNet-Page-Method-using-jQuery-AJAX-Example.aspx
I have asp.net application where need to implement autocomplete, I try to load list of names from server side and then deserealize it in js code, but have an 500 error, can anybody help me?
Unknown web method GetListofCompanies.
Parameter name: methodName
Code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetListofCompanies(string name) {
var companies = _companyRepo.GetAll().Select(x => x.Name).ToList();
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(companies);
return strResponse;
}
JS:
var name = "";
$.ajax({
url: "Company.aspx/GetListofCompanies",
type: "post",
data: { name: name },
dataType: "json",
contentType: 'application/json',
success: function (data) {
// Get the data.
var responseArray = JSON.parse(data.d);
$("#txtName").autocomplete({
source: responseArray
});
}
});
// Namespaces.
using System.Web.Services;
using System.Web.Script.Serialization;
[WebMethod]
public static string GetListofCompanies(string name)
{
List<string> companies = new List<string>();
companies.Add("Company1");
companies.Add("Company2");
companies.Add("Company3");
companies.Add("Company4");
companies.Add("Company5");
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(companies);
return strResponse;
}
// JS
function request() {
var name = "";
var data = { name: name };
$.ajax({
url: "Default.aspx/GetListofCompanies",
type: "POST",
contentType: 'application/json',
data: JSON.stringify(data)
}).success(function (data) {
// do your stuff here
})
.fail(function (e) {
alert("Error");
});
}
I have a problem related the ajax call request searched for it on stack overflow tried all the related help that i got but can't solve the problem. the problem is that i request to a controller from my view using this code.
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var dataJson = {"contactNumber": number};
$.ajax({
type: "POST",
url: "../contactWeb/messages",
data: JSON.stringify(dataJson),
//data: dataJson,
//contentType: "application/json",
contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
and the controller that receives the call is
[HttpPost]
public JsonResult messages(string dataJson)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , dataJson);
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
but it passes NULL value to the controller
There are couple of issues need to be fixed
whats the need of
JsonRequestBehavior.AllowGet
when your action type is post.
If you are using asp.net mvc4 use Url.Action to specify url i.e
url:"#Url.Action("ActionName","ControllerName")"
Now Talking about your issue.
Your parameter names must match, change dataJson to contactNumber.Though its ok to use there isnt any need to use JSON.stringify as you are passing single string parameter.
[HttpPost]
public JsonResult messages(string contactNumber)
{
Int64 userID = Convert.ToInt64(Session["userId"]);
Hi could you change the name of your parameters string dataJson in your action to contactNumber in respect to the object you pass via your Ajax call
[HttpPost]
public JsonResult messages(string contactNumber) //here
{
Int64 userID = Convert.ToInt64(Session["userId"]);
try
{
List<MessagesModel> messagesModel = new List<MessagesModel>();
IMessages MessageObject = new MessagesBLO();
messagesModel = MessageObject.GetAllMessagesWeb(userID , contactNumber); //and here
//ViewData["Data"] = messagesModel;
}
catch (Exception e)
{
}
//return View();
string msg = "Error while Uploading....";
return Json(msg, JsonRequestBehavior.AllowGet);
}
If you want to get JSON in messages() try this:
<script type="text/javascript">
$(document).ready(function () {
$('#contactDiv ').click(function() {
var number = $(this).find('.ContactNumber').text();
var data = {"contactNumber": number};
var dataJson = JSON.stringify(data);
$.ajax({
type: "POST",
url: "../contactWeb/messages",
dataType: 'text',
data: "dataJson=" + dataJson,
//data: dataJson,
//contentType: "application/json",
cache: false,
success: function (msg) {
//msg for success and error.....
alert(msg);
return true;
}
});
});
});
</script>
I have been working with Web API and found an interesting observation that I am not able to understand.
controller:
public class UserController: ApiController
{
public void Post(MyViewModel data)
{
//data is null here if pass in FormData but available if its sent through Request Payload
}
}
viewModel
public class MyViewModel{
public long SenderId { get; set; }
public string MessageText { get; set; }
public long[] Receivers { get; set; }
}
JS that is not working
var usr = {};
usr.SenderId = "10";
usr.MessageText = "test message";
usr.Receivers = new Array();
usr.Receivers.push("4");
usr.Receivers.push("5");
usr.Receivers.push("6");
$.ajax(
{
url: '/api/User',
type: 'POST',
data: JSON.stringify(usr),
success: function(response) { debugger; },
error: function(error) {debugger;}
});
JS that is working
var usr = {};
usr.SenderId = "10";
usr.MessageText = "test message";
usr.Receivers = new Array();
usr.Receivers.push("4");
usr.Receivers.push("5");
usr.Receivers.push("6");
$.post( "/api/User", usr)
.done(function( data ) {
debugger;
});
So, if I pass on $.ajax with lots of other configuration like type, contentType, accept etc, it still don't bind model correctly but in case of $.post it works.
Can anybody explain WHY?
Try looking at what gets POSTed when you try it with $.ajax (e.g. with Fiddler of F12 tools of your choice). It can very well be that jQuery passes the data as URL-encoded string rather that as JSON literal.
To fix the issue try specifying dataType together with contentType parameter. Also, I don't think you need JSON.stringify, just pass the JSON literal you're creating:
$.ajax({
data: usr,
dataType: 'json',
contentType: 'application/json',
/* The rest of your configuration. */
});
Here's the TypeScript method that we use in one of our projects (ko.toJSON returns a string representing a JSON literal passed as a method parameter):
public static callApi(url: string, type?: string, data?: any): RSVP.Promise {
return new RSVP.Promise((resolve, reject) => {
$.ajax('/api/' + url, {
type: type || 'get',
data: data != null ? ko.toJSON(data) : null,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: () => {
resolve.apply(this, arguments);
},
error: () => {
reject.apply(this, arguments);
}
});
});
}
Hope this helps.