Get Value from view to controller - json

I need to assign value from from view to model and from model to controller.
I am new to MVC and i dont know how can i pass those values.
MODEL- public gulb StringValue {get;set;}
view -
$.ajax({
url: "/Home/ValidateMembership",
type: 'GET',
data: { StudentDOB: StudentDOB, ssn: ssn },
dataType: 'text',
success: function (result) {
var deserializedResult = JSON.parse(JSON.parse(result));
if (deserializedResult.StatusCode == 1) {
memberFoundCurrent();
Model.StringValue = deserializedResult.ContactId;
}
}
});
controller :- needValue = StringValue.
I am not able to store value to Model.Stringvalue, it throws an error. How am i suppose to store the value to Model so that i can use it on controller needvalue

We can easily pass a value from view to controller. Try the following, I changed little bit as per the above
view -
var student = {}; //for ex: student is your model name
student. StringValue = “some value”
$.ajax({
url: "/Home/ValidateMembership",
type: 'GET',
data: '{student: ' + JSON.stringify(student) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var deserializedResult = JSON.parse(JSON.parse(result));
if (deserializedResult.StatusCode == 1) {
memberFoundCurrent();
Model.StringValue = deserializedResult.ContactId;
}
}
});
Also refer to this link: https://www.aspsnippets.com/Articles/Pass-Send-Model-object-in-jQuery-ajax-POST-request-to-Controller-method-in-ASPNet-MVC.aspx
It will give you detailed idea. Hope it was useful kindly let me know your thoughts or feedback.
Thanks
Karthik

Related

how to pass serialize data and stringified data together in ajax

I have a ajax function where i am passing two objects:
1) serialize form data object
2) complex object
Ajax function:
var temp = sessionStorage.getItem('book');
var viewName = $.parseJSON(temp);
var ViewModel = $("#OffsetBookForm").serialize();
$.ajax({
contentType: "application/json; charset=utf-8",
type: "Post",
url: "#Url.Content("~/Estimate/CreateOrder")",
data: JSON.stringify({ 'OffsetCommonObj': ViewModel, 'obj': viewName }),
dataType: 'json',
success: function (data) {
}
});
And My ActionMethod:
public ActionResult CreateOrder(EstimationOffsetViewModel OffsetCommonObj,
OffsetCostCalculation obj)
{
// do something here..
}
My problem is, the first object in action method i.e-"OffsetCommonObj" is getting null. What am I doing wrong in the code? Please Help..Thanks.

Why can I not extract the data from this basic JSON Example

This is my Java script
function displayCustomerData( p_customername )
{
$.ajax({
url: 'myservlet',
type: 'GET',
data: { requesttype : "getcustomerdata" ,
customername : p_customername } ,
contentType: 'application/json; charset=utf-8',
success: function ( data )
{
$("#usernametxt").val( data.customer);
},
error: function () {
alert("Error loading customer data");
}
});
on the server side I generate the JSON using the Gson library
Gson gson = new Gson();
return gson.toJson( customerData );
customerData is a simple POJO with two String fields
I have a breakpoint at the Success response from the server
This is what the "data" variable contains in my debugger when I try to get the data from it
data "{"customer":"cuatomer A","userName":"user A"}"
but on my browser console when I do "data.customer" it tells me that customer is undefined ?
This indicates that there is something wrong with the JSON data but I don't see anything wrong and I can't stare at it any longer... anyone see anything?
I have tried it on Chrome and Firefox incase it was a browser issue, same problem on both.
you can parse the Data like using JSON.parse(data) and try for data.customer u can get .the result ....
function displayCustomerData( p_customername )
{
$.ajax({
url: 'myservlet',
type: 'GET',
data: { requesttype : "getcustomerdata" ,
customername : p_customername } ,
contentType: 'application/json; charset=utf-8',
success: function ( data )
{
var data1 = JSON.parse(data);
$("#usernametxt").val( data1.customer);
},
error: function () {
alert("Error loading customer data");
}
});

JSON passed to controller has no value

I am unable to get my JSON to my controller, and I can't figure out why the value I get in javascript isn't being passed to the controller. Here is my ajax post in my javascript:
this.save = function () {
var data = ko.toJSON(this.Routines);
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
now data contains
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
which is what I want, but the controller shows nothing. Here is my controller
[HttpPost]
public JsonResult CreateJson(t_routine routine, string data)
{
var message = "success";
return Json(message);
}
As I understand it, MVC 3+ automatically receives JSON without any need for parameters like my string data, I just threw it in there to try and figure out if I'm getting anything at all. data is null and routine shows 0's and null for values. What am I missing?
If t_routine represents the server side type for
[{"routine_name":"new routine","duration":"20","rest":"10","rounds":1}]
Then it might be enough to call JSON.stringify on the ko.toJSON result like this
this.save = function () {
var data = JSON.stringify(ko.toJSON(this.Routines));
$.ajax({
type: 'POST',
url: "CreateJson",
data: data,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
if (!result.success)
alert("test")
else { }
}
})
}
the data parameter on your controller action is not needed then and you most likely need to change the t_routine parameter to t_routine[]

Json Data Not mapped in the backend service

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');
}
});

Jquery Autocomplete with json and using parameters

I am trying to do an autocomplete input field. Everytime a user type a letter in that field, the value of the field is sent to the server and the server answer with words that match.
var acOptions = {
source:function (request, response) {
$.ajax({
url: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw",
type: "GET", dataType: "json",
data: { expr: request.term},
success: function (data) {
response($.map(data, function (item) {
return item.value;
}))
}
})
},
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
This is an example of data from the server:
[{"value":"Greater"},{"value":"great"},{"value":"greatly"},{"value":"Greater-Axe"}]
The previous code do the right request to the server (and the server answer right) but it does not display anything in the text field.
I tried to do the autocomplete without an explicit ajax object but then I couldn't send the current value of the field (parameter "expr" of the request) to the server:
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=",
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);
Thank you for your help!
You can use jQuery to pull the value of your field to add it to URL parameter string.
var acOptions = {
source: "index.php?option=com_fmw&view=keywords_api&controller=keywords_api&format=raw&expr=" + $('#ID_OF_YOUR_TEXTBOX').val(),
minChars: 1,
dataType: 'json'
};
$( "#search_box_input" ).autocomplete(acOptions);