I have created and filled various arrays using jquery. First time, trying to send JavaScript arrays to MVC controller.
Can I have an example how to do that? How can I send the arrays and other variables as well? On the controller side, how can I retrieve the data?
You'll probably want to use jQuery.ajax, with a dataType parameter of 'json'. You can send any JSON object. Possible example:
var obj = {'foo': 'bar'};
$.ajax({
type: "POST",
url: "some.aspx",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: obj,
success: function(resp){
alert("Response: " + resp);
}
});
You can comma or pipe delimit your input and on the other end just parse it to keep things simple. Or if you want to do things the right object oriented way you could use the following code:
var object1 = $(".ControlArrayClass").val();
var object2 = $(".ControlArrayClass2").val();
$.post('mycontroller/myactionmethod', function( variable1: object1, variable2: object2});
and on the controller end it would look like this
public ActionResult myactionmethod(Guid[] variable1, String[] variable2)
{
//do whatever here
return View();
}
Hope this helps.
Related
I'm attempting to access data from a form and pass it to a controller in MVC.
I was successful in passing the data when I get the element by ID and pass as string:
This works:
data: JSON.stringify({
'Answer0': $("#Answer0").val(),
'Answer1': $("#Answer1").val(),
'Question0': $("#Question0").val()
}),
However I want to bring the data in as a viewmodel. When I specify the request as:
data: JSON.stringify($('#' + formDiv).serializeObject()),
It will populate the viewmodel, however there are fields that are not bound to the ViewModel that I would like to pass along with the serialized form. I have tried just adding them, but they don't seem to come in if I pass both the serialized form object and the additional string.
function clickedNext(e, formDiv) {
var sURL = '#Url.Action("SurveySave", "Home")'
$.ajax({
url: sURL,
type: "POST",
contentType: 'application/json',
data: JSON.stringify($('#' + formDiv).serializeObject(), { 'Answer0': $("#Answer0").val(), 'Answer1': $("#Answer1").val() }),
success: function (data) {
//$('#InvestigationStatus').html(data);
}
});
Controller
[HttpPost]
public ActionResult SurveySave(SurveyViewModel s, string Answer0, string Answer1)
I feel like you can't put two objects inside of JSON.stringify();
Maybe try something like:
var bothObjects = {
$('#' + formDiv).serializeObject(),
{ 'Answer0': $("#Answer0").val(), 'Answer1': $("#Answer1").val() }
}
...
JSON.stringify(bothObjects),
I need to make a request as follows:
var url="http://127.0.0.1:8080/simulate/";
$.ajax({
url: url,
type: 'POST',
data:{ student_num:10,
company_num:10,
students:"",
csrfmiddlewaretoken:'{{csrf_token}}',
companies:[{weight:10},{weight:11},{weight:9}]
},
success: function(data, textStatus, xhr) {
var text=xhr.responseText
console.log(text)
}
});
But in this way, the request.POST object is not organizing the companies into a nested json array. Instead it makes it into a 2D array as follows:
<QueryDict: {u'student_num': [u'10'], u'students': [u''], u'companies[2][weight]': [u'9'], u'companies[1][weight]': [u'11'], u'company_num': [u'10'], u'companies[0][weight]': [u'10'], u'csrfmiddlewaretoken': [u'RpLfyEnZaU2o4ExxCVSJkTJ2ws6WoPrs']}>
In this way, I feel hard to reorganize the companies into a list of objects. I checked some other questions, some people say we should do this:
companies:"[{weight:10},{weight:11},{weight:9}]"
And then use json.loads to parse the string back to a list of objects. But I am keep getting parsing error if I use codes like this:
company_array = request.POST['company_array']
company_array = json.loads(company_array)
or this:
company_array = json.load(StringIO(company_array))
So what should be the correct way to handle nested JSON object?
You should use JSON.stringify() to stringify your data before sending it:
$.ajax({
url: url,
type: 'POST',
data: { data: JSON.stringify({ student_num:10,
company_num:10,
students:"",
csrfmiddlewaretoken:'{{csrf_token}}',
companies:[{weight:10},{weight:11},{weight:9}]
}) },
success: function(data, textStatus, xhr) {
var text=xhr.responseText
console.log(text)
}
});
Then you can parse with json.loads() on the server side:
data = json.loads(request.POST.get('data'))
You might find the answers here useful: Reading multidimensional arrays from a POST request in Django
You can try look to django-SplitJSONWidget-form and get decision from it.
I am developping a wordpress plugin, want to send string as post ajax parameters, but the string breaks with '&'
code is
var data = "http://localhost/wordpress/?page_id=1&setval=RFZ83WSXa816yc6DNcgfHlgIkztR7KEC6JHRHCCcwfw|~HBZW9j3B59f8rCXO_QLY-gG2MDAcKo6fKG2AnbYnMns|~KA1KUT_SuU9W2UDTnngTsbJiptTvGWZAAzTfN5BCHak|~1";
$.ajax({
data: data
type: "POST",
url: '<?php echo plugins_url().'/page-loader/createMetaDetails.php'; ?>',
data :data,
success: function(msg){
alert('wow'+msg);
}
});
it is not working only passing till 'http://localhost/wordpress/?page_id=1', why?
You need to put data in key value pair array to pass jquery ajax function.
change
var data = 'http://localhost/wordpress/?page_id=1&setval=RFZ83WSXa816yc6DNcgfHlgIkztR7KEC6JHRHCCcwfw|~HBZW9j3B59f8rCXO_QLY-gG2MDAcKo6fKG2AnbYnMns|~KA1KUT_SuU9W2UDTnngTsbJiptTvGWZAAzTfN5BCHak|~1'
To
var data = { yoururl:'http://localhost/wordpress/?page_id=1&setval=RFZ83WSXa816yc6DNcgfHlgIkztR7KEC6JHRHCCcwfw|~HBZW9j3B59f8rCXO_QLY-gG2MDAcKo6fKG2AnbYnMns|~KA1KUT_SuU9W2UDTnngTsbJiptTvGWZAAzTfN5BCHak|~1'}
The data property should be a Javascript object in key:value format; the keys will be the form field names.
I'm trying to execute a cross domain request for data from a wordpress blog using YQL. This is the code from my first attempt:
var g = {data:""}
function getWP() {
var targeturl = "http://www.mysite.com";
var url = "http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(targeturl)+
"%22&format=xml'&callback=?";
var successfunc = function(data) {
if(data.results[0]){
g.data = data.results[o];
} else {
var errormsg = '<p>Error: could not load the page.</p>';
alert(errormsg);
}
}
$.ajax({
url: url,
success: successfunc
});
}
When I tried this ajax call, the data object returned was an empty string. However, when I did this:
$.getJSON(url, successfunc);
the proper JSON object was returned. What is the difference between the two calls? And more importantly, why did only the second one work?
The difference is that you are not specifying your data type or content type
Add
$.ajax({
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: successfunc
});
to your ajax call
$.getJSON() uses data type json while the $.ajax() doesn't. If you want to use standard $.ajax() you'll have to specify datatype explicitly. For cross-domail calls use datatype jsonp instead of json. But I think YQL works with json as well.
I want to pass an array of strings from my view model (in form of an ko.observableArray) to the controller in Asp.net MVC.
As the ko.observableArray is an object rather than array, it cannot simply be passed through the $.ajax method and used as array in controller side.
How can I pass the data in ko.observableArray to controller so that I can use it as array on the controller side?
Knockout has two utility function called ko.toJS and ko.toJSON.
var myPlainObject = ko.toJS(root) will traverse your object and turn any observable into a plain JavaScript property.
var myJSONstring = ko.toJSON(root) will do the same and then do a JSON.stringify on the result.
So, you can use those functions on your viewModel to get plain JavaScript objects.
Info from the docs here.
If the items in your observableArray do not contain observables, then you could simply just retrieve the underlying array by doing myObservableArray()
Update: based on comment. This works fine for me:
var viewModel = {
items: ko.observableArray(["one", "two", "three", "four"]),
sendItems: function() {
$.ajax({
type: "POST",
url: "#Url.Action("Test")",
data: ko.toJSON(viewModel.items),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data) {
alert(ko.toJSON(data));
}
}
});
}
};
Against an action like:
//just echo back data
public JsonResult Test(List<String> myList)
{
return Json(myList);
}
Does this match what you are trying?