I have found several answers (here for example) but they do not seem to solve my problem.
var result = {
command: 'exportWAV',
type: type
};
$.ajax({
url: 'SubmitSound',
type: 'Post',
data: JSON.stringify(result),
contentType: 'application/json; charset=utf-8',
success: function (msg) {
alert(msg);
}
});
Back end code
[HttpPost]
public ActionResult SubmitSound(string blob)
{
// Create the new, empty data file.
string fileName = AppDomain.CurrentDomain.BaseDirectory + "/Content/Sound/" + Environment.TickCount + ".wav";
FileStream fs = new FileStream(fileName, FileMode.CreateNew);
BinaryWriter w = new BinaryWriter(fs);
w.Write(blob);
w.Close();
fs.Close();
return new JsonResult() { Data = "Saved successfully" };
}
result is not null because this.postMessage = result; send a file back to client side for downloading. w.Write(blob) keeps complaining that blob cannot be null.
How can I make it work? Thank you and best regards
Do this:
data: JSON.stringify({ blob: result}),
You may want to change your string param in your controller action, for an object with the same structure of your JSON... that means the same attributes names.
The object should be something like this:
public class MyBlob{
public string command {get; set;}
public string type {get; set;}
}
So, your action should be:
public ActionResult SubmitSound(MyBlob blob){
//Here your action logic
}
Related
I try so many times to do below these code . but it still recive the value is null.
var cartViewModel = [];
$(":text").each(function (i) {
var quantity = parseInt($(this).val());
var id = parseInt($(this).data("id"));
cartViewModel.push({ id: id, quantity: quantity });
}
and next I use $.post to submit cartViewModel
the code such like:
var data= { data: JSON.stringify(cartViewModel) };
$.post(url,data,function(json){
//....
});
public class ShoppingCartViewModel
{
public int Id { get; set; }
public int Quantity { get; set; }
}
[HttpPost]
public ActionResult SubmitCart(List<ShoppingCartViewModel> models)
{
return Json(result);
}
but the arg 'models' also is null, I feel very confused. who can point out the right way. thx!
The model binder is expecting a property named models, but you're using the name data. What happens if you change
var data= { data: JSON.stringify(cartViewModel) };
to
var data= { models: JSON.stringify(cartViewModel) };
Edit:
The reason your models property is now empty is because you're calling JSON.stringify(cartViewModel). Instead of passing the action an array of objects, your passing it a string (that happens to be a representation of an array of objects).
Change your data definition to:
var data = { models: cartViewModel };
Edit again:
The above works fine for MVC5. It does not work in MVC4. To make it work in MVC4:
$.ajax({
type: 'POST',
url: '#Url.Action("Add", "Home")',
data: JSON.stringify({ models: cartViewModel }),
contentType: 'application/json',
});
I have the this code to post json to a controller.
The problem is that the credentials object does not get populated with the posted values.
How do I change this code so that it works?
I see in Fiddler that the request is being posted correctly.
[HttpPost]
public JsonResult Authenticate(CredentialsModel credentials)
{
return Json(credentials);
}
[DataContract]
public class CredentialsModel
{
[DataMember(Name = "user")]
public string User;
[DataMember(Name = "pass")]
public string Pass;
}
$.ajax({
type: "POST",
url: "/login/authenticate",
cache: false,
contentType: "application/json; charset=utf-8",
data: '{"user":' + JSON.stringify($('#username').val()) + ',"uass":' + JSON.stringify($('#userpass').val()) + '}',
dataType: "json",
timeout: 100,
success: function (msg) {
},
complete: function (jqXHR, status) {
if (status == 'success' || status == 'notmodified') {
var obj = jQuery.parseJSON(jqXHR.responseText);
}
},
error: function (req, status, error) {
}
});
The default MVC model binder only works with properties. Your CredentialsModel is using fields. Try changing them to properties. You can also remove the annotations.
public class CredentialsModel
{
public string User { get; set; }
public string Pass { get; set; }
}
Also, as pointed out by Sahib, you can create a Javascript Object and then stringify it, rather than stringifying each one. Although that doesn't appear to be the problem in this case.
data: JSON.stringify({
User: $('#username').val(),
Pass: $('#userpass').val()
})
Try chaning your data like this :
$.ajax({
.................
//notice the 'U' and 'P'. I have changed those to exactly match with your model field.
data: JSON.stringify({User: $('#username').val(),Pass: $('#userpass').val()}),
.................
});
I am working on SpringMVC, I am passing data from ajax to controller but i got null value in my controller please check my code below
function searchText()
{
var sendData = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
url: "/gDirecotry/ajax/searchUserProfiles.htm,
async: true,
data:sendData,
success :function(result)
{
}
}
MyControllerCode
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(HttpServletRequest request)
{
String pName = request.getParameter("pName");
//here I got null value
}
any one help me
Hey enjoy the following code.
Javascript AJAX call
function searchText() {
var search = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url: "/gDirecotry/ajax/searchUserProfiles.html",
data: JSON.stringify(search), // Note it is important
success :function(result) {
// do what ever you want with data
}
});
}
Spring controller code
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(#RequestBody Search search, HttpServletRequest request) {
String pName = search.getPName();
String lName = search.getLName();
// your logic next
}
Following Search class will be as follows
class Search {
private String pName;
private String lName;
// getter and setters for above variables
}
Advantage of this class is that, in future you can add more variables to this class if needed.
Eg. if you want to implement sort functionality.
Use this method if you dont want to make a class you can directly send JSON without Stringifying. Use Default Content Type.
Just Use #RequestParam instead of #RequestBody.
#RequestParam Name must be same as in json.
Ajax Call
function searchText() {
var search = {
"pName" : "bhanu",
"lName" :"prasad"
}
$.ajax({
type: "POST",
/*contentType : 'application/json; charset=utf-8',*/ //use Default contentType
dataType : 'json',
url: "/gDirecotry/ajax/searchUserProfiles.htm",
data: search, // Note it is important without stringifying
success :function(result) {
// do what ever you want with data
}
});
Spring Controller
RequestMapping(value="/gDirecotry/ajax/searchUserProfiles.htm",method=RequestMethod.POST)
public #ResponseBody String getSearchUserProfiles(#RequestParam String pName, #RequestParam String lName) {
String pNameParameter = pName;
String lNameParameter = lName;
// your logic next
}
I hope, You need to include the dataType option,
dataType: "JSON"
And you could get the form data in controller as below,
public #ResponseBody String getSearchUserProfiles(#RequestParam("pName") String pName ,HttpServletRequest request)
{
//here I got null value
}
If you can manage to pass your whole json in one query string parameter then you can use rest template on the server side to generate Object from json, but still its not the optimal approach
u take like this
var name=$("name").val();
var email=$("email").val();
var obj = 'name='+name+'&email'+email;
$.ajax({
url:"simple.form",
type:"GET",
data:obj,
contentType:"application/json",
success:function(response){
alert(response);
},
error:function(error){
alert(error);
}
});
spring Controller
#RequestMapping(value = "simple", method = RequestMethod.GET)
public #ResponseBody String emailcheck(#RequestParam("name") String name, #RequestParam("email") String email, HttpSession session) {
String meaaseg = "success";
return meaaseg;
}
i am trying to pass List from view to controller but i am getting null value. code is written as follows :
model class :
public class testModel
{
public int ID { get; set; }
public string Name { get; set; }
public List<myModel> ParameterList {get;set;}
}
jquery and ajax code to post data to controller :
var myModel = {
"Name":"test",
"Description":"desc"
};
var Object = {
Name: $("#Name").val(),
ParameterList : myModel
};
$.ajax({
url: '/controller/action',
type: 'POST',
data: JSON.stringify(Object),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) { }
else { }
}
});
i am getting value for Name property but not for ParameterList.
What is wrong here ? am i missing anything ?
Please help me out.
Thanks
Edit : Controller Code from comments,
public JsonResult Save(Object Obj)
{
// logic for managing model and db save
}
You said,
I am getting value for Name property but not for ParameterList.
Which makes me wonder what is the structure of myModel, as you have declared ParameterList as a list of myModel type : List<myModel> ParameterList
Also I would recommend you to log JSON.stringify(Object) to console and check the Json value you are actually posting to the controller.
Here is what I found you must be posting back
{"Name":"yasser","ParameterList":{"Name":"test","Description":"desc"}}
Also read these articles :
How can I pass complex json object view to controller in ASP.net MVC
Pass JSON object from Javascript code to MVC controller
Try this:
var myModel = [{
"Name":"test",
"Description":"desc"
}];
var Object = {
Name: $("#Name").val(),
ParameterList : myModel
};
$.ajax({
url: '/controller/action',
type: 'POST',
data: Object,
dataType: 'json',
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) { }
else { }
}
});
Just try like this..Hope this would help!!
script:
var emp = [{ 'empid': 1, 'name': 'sasi' },{ 'empid': 2, 'name': 'sathish'}];
emp = JSON.stringify(emp)
$.post("/Home/getemplist/", { 'emp': emp })
Controller:
Here i just changed the parameter to string type. using JavaScriptSerializer you can able to convert this string data to your class list objects.. you can understand it better if u see my code below:
public void getemplist(string emp)
{
List<Emp> personData;
JavaScriptSerializer jss = new JavaScriptSerializer();
personData = jss.Deserialize<List<Emp>>(emp);
// DO YOUR OPERATION ON LIST OBJECT
}
I am using revealing module pattern and knockout to bind a form. When data is entered in that form(registration), it needs to be posted back to MVC4 web method.
Here is the Jquery code
/*
Requires JQuery
Requires Knockout
*/
op.TestCall = function () {
// Private Area
var _tmpl = { load: "Loading", form: "RegisterForm"};
var
title = ko.observable(null)
template = ko.observable(_tmpl.load),
msg = ko.observable(),
postData = ko.observable(),
PostRegistration = function () {
console.log("Ajax Call Start");
var test = GetPostData();
$.ajax({
type: "POST",
url: obj.postURL, //Your URL here api/registration
data: GetPostData(),
dataType: "json",
traditional: true,
contentType: 'application/json; charset=utf-8'
}).done(Success).fail(Failure);
console.log("Ajax Call End");
},
GetPostData = function () {
var postData = JSON.stringify({
dummyText1: dummyText1(),
dummyText2: dummyText2(),
});
return postData;
}
return {
// Public Area
title: title,
template: template,
dummyText1: dummyText1,
dummyText2: dummyText2
};
}();
The controller code is simple as per now
// POST api/registration
public void Post(string data)
{
///TODO
}
When i am trying to, capture the data (using simple console.log) and validate it in jslint.com, it's a valid Json.
I tried hardcoding the data as
data: "{data: '{\'name\':\'niall\'}'}",
But still i get as null, in my web method.
Added the tag [System.Web.Script.Services.ScriptMethod(UseHttpGet = false, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] to my Post method in controlled, but still no fruitful result
Even tried JSON.Stringify data: JSON.stringify(data) but still i get null in my web-method.
I am not able to figure out the solution.
Similar issue was found # this link
http://forums.asp.net/t/1555940.aspx/1
even Passing parameter to WebMethod with jQuery Ajax
but didn't help me :(
MVC and WebApi uses the concept of Model Binding.
So the easiest solution is that you need to create a Model class which matches the structure of the sent Json data to accept the data on the server:
public void Post(MyModel model)
{
///TODO
}
public class MyModel
{
public string DummyText1 { get; set; }
public string DummyText1 { get; set; }
}
Note: The json and C# property names should match.
Only escaped double-quote characters are allowed, not single-quotes, so you just have to replace single quotes with double quotes:
data: "{data: '{\"name\":\"niall\"}'}"
Or if you want to use the stringify function you can use it this way:
data: "{data: '" + JSON.stringify(data) + "'}"