How to pass an ko.observableArray to an MVC controller? - asp.net-mvc-3

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?

Related

Returning data objects from ajax query to controller

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),

How can we retrieve json object from index action of a controller in mvc and fill in a viewmodel

In my quiz application I can call a controller's action and fill in my viewmodel using the ajax calls (as the code below) but how can I load the question object on the index action and fill in my viewmodel before I make subsequent ajax calls on submit button click. In simple words how to get Json object on page load and fill the model
var question = {};
// fill the viewmodel object.
$.ajax
{
url: 'Tools/Survey/',
data: JSON.stringify({question : question }),
contentType: 'application/json',
dataType: 'json',
type: 'POST',
success: function (data) {
// data contains next question and create the view accordingly
},
error: function () {
// error
}
});
Don't use JSON.stringify. Now you are sending one string. If you don't stringify input, values will be sent like in regular POST. Just write this instead:
data: {question : question},

how to get the result from controller in ajax json

Isend the some aruguments to controller using ajax but it does not return the value.
My concept : selected #html.dropdownlist value i send to the controller , using this value thats perfrom the get the valus for bind the property to another dropdownlist using mvc3
IGot this answer : verfif given link
verfif given link
you are passing type option in ajax twice and the url is not formatted properly
function onChange(bookid) {
$.ajax({
type: "GET",
url: '#Url.Action("books","subject")',
data : { bookid: bookid},
dataType: "json",
success: function (result) {
alert('success');
//do whatever you want
},
error: function(result){
}
});
};
You are passing dataType as json. So, if you want to hit the success result for $.ajax, you need to return Json from your action result instead of returning as View.
When you return as View it gives error always.
public ActionResult books(string bookid)
{
var books= service.books(projectId);
// books are stored in list format
return Json(books);
}
Hope it helps you.

MooTools: How do package data for a POST ajax request?

I'm using MooTools 1.4.1. I want to create an ajax post requst, but I can't figure out how to construct the "data" attribute, which I wish to contain the name value pairs of a form whose id is "myForm".
$('save').addEvent('click', function(event) {
var req = new Request({
method: 'post',
url: 'save',
data: { ... },
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
});
});
Anyone know how I should populate the "data" attribute? Thanks, - Dave
You can use
$('myForm').toQueryString();
Alternatively, The MooTools More package has a Form.Request() class to send a Form using Ajax.
As Savageman commented, you can throw your form element into toQueryString() and send it through in the data property, or by running .send() or .post() on the request object.
You also seem to be missing a closing squiggly bracket.
Anyhow, this is how I make AJAX requests:
new Request({
url: 'http://url/to/ajax/script.php',
onSuccess: function(data) {
doStuff();
}
}).post('action=foo&bar=baz');
I'd recommend you use Request.JSON if you're planning on sending stuff back. It's less "shotgun approach"-ey.
You can just pass form element to "data" property, and conversion is automatic.
var req = new Request({
method: 'post',
url: 'example.com/form.php',
data: $('myForm'),
onRequest: function() {
// on request
},
onComplete: function(response) {
alert(response);
}
});
data - (mixed: defaults to '') The default data for Request:send, used when no data is given. Can be an Element, Object or String.
If an Object is passed the Object:toQueryString method will be used to convert the object to a string.
If an Element is passed the Element:toQueryString method will be used to convert the Element to a string.
http://mootools.net/docs/core/Request/Request

How to send multiple jQuery arrays to an MVC controller?

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.

Resources