Model Bind to a List<> when Posting JavaScript Data Object - javascript

I'm trying to post a JavaScript data object with the following:
$.post(frm.attr("action"), data, function(res)
{
// do some stuff
}, "json");
where 'data' takes the structure of
data
- panelId
- siteId
- ConfiguredFactsheetId // this is an array of CheckBox ids that correspond to ConfiguredFactsheets
- 123
- 234
- 345
With this, both site & panel are correctly instantiated & bound with their data but the List object is null.
public JsonResult Edit(Site site, Panel panel, List<ConfiguredFactsheet> configuredFactsheets)
{
// do stuff
return Json(success);
}
Now, I realise that my 'data' object's ConfiguredFactsheetId property is just an array of id values. Do I need to specify that each value corresponds to a configuredFactsheetId property of my ConfiguredFactsheet object? If so, my data object would take a form similart to
data
- panelId
- siteId
- ConfiguredFactsheet // this is an array of CheckBox ids that correspond to ConfiguredFactsheets
- ConfiguredFactsheetId:123
- ConfiguredFactsheetId:234
- ConfiguredFactsheetId:345
but this obviously won't work because every time I add a new ConfiguredFactsheetId to the object, it'll just overwrite the previous one.
I know I can do this if I built a query string of the form
"&ConfiguredFactsheet[i].configuredFactsheetId = " + configuredFactsheetId;
but I'd like to contain everything in a single data object
Any suggestions? Do I need to explain anything (probably everything!) more clearly?
Thanks
Dave

In the end, this worked:
var valuesArray = objCheckBoxes.map(function()
{
return $.getAttributes($(this));
});
var obj = new Array();
$.each(valuesArray, function(item) { obj.push($(this)[0]); });
$.each(obj, function(i)
{
// basically I take the rule where you need to append
// the index to the type, and I apply it here.
data["configuredFactsheets[" + i + "].configuredFactsheetId"] = $(this).attr("configuredFactsheetId");
});
Note: read about $.getAttributes

An alternative is to post:
?myValues=1&myValues=2&myValues=3
And accept it as an IEnumerable
public ActionResult DoSomething(IEnumerable<int> myValues) {
...

Related

Restoring values to tokeninput field - jquery error

I'm trying to take values from a tokeninput field, save them to localstorage then retrieve them later. I am getting an error. Code:
//Save to storage
var selectedValues = $('#Contacts').tokenInput("get");
console.log(JSON.stringify(selectedValues));
localStorage.setItem('ContactsJSON', JSON.stringify(selectedValues));
//Restore
var names = localStorage.getItem("ContactsJSON");
console.log(names);
$.each(names, function (index, value) {
$("#Contacts").tokenInput("add", value);
});
Error message is:
Invalid operand to 'in': Object expected
Error is showing at jquery-1.10.2.js (1009,2)
I'm quite sure that my JSON is correct, as per the tokeninput docs, it should be in the right format when retrieved using the get API:
selector.tokenInput("get");
Gets the array of selected tokens from the tokeninput (each item being an object of the kind {id: x, name: y}).
The data I can see in localstorage is as follows:
[{id":59,"name":"Steve Carrell"},{"id":58,"name":"John Krasinski"},{"id":1,"name":"Jenna Fischer"}]
I believe that your problem is that you are getting string, not an object.
You should call JSON.pase() on your string from localstorage.
So, fixed code should look like:
// here you are converting object to string:
localStorage.setItem('ContactsJSON', JSON.stringify(selectedValues));
var names = localStorage.getItem("ContactsJSON");
// here you should convert string back to object
var names_object = JSON.parse(names);
console.log(names_object);
$.each(names_object, function (index, value) {
$("#Contacts").tokenInput("add", value);
});

AngularJs pass model value + model name to function in controller

$scope.populateMap=[{name: "ABC", code: "123"}, {name: "XYZ", code: "345"}]
//Want to send model name + value of model Currently sending ngObject.MainObj.specificFormatObj
HTML
<select ng-model="ngObject.MainObj.specificFormatObj" ng-change="ngObject.MainObj.specificFormatObj">
<option></option>
<option ng-repeat="i in populateMap" value="{{i}}">{{i.name}}</option>
JS
// CONTROLLER CODE JSON parse object to get name and code GOT parsedObj
$scope.genericSetLookups=function (Obj) { // want to do something like get the ngmodel string + the value, currently only value comes in
Obj.code=parsedObj.code;
Obj.name=parsedObj.name
};
More Explanation: ngObject.MainObj.specificFormatObj
I want in my model to store value of lookups in a specific way, with name and code. On the UI I populate using ng-repeat , So when I select a particular value I can either take i.name as display and set value as i.code .
But if i do that my ngObject.MainObj.specificFormatObj.name will be null and the value will get set to ngObject.MainObj.specificFormatObj.code by using ng-model ,so that is the reason in value I am taking i, not i.code or i.value ,now in the map i have code and name pair.
I sent it to a function and parse it, and set the value to ngObject.MainObj.specificFormatObj.code=inputTofunc.code respectively for name. In this case in the ng-change i pass on the ngObject.MainObj.specificFormatObj.code ,rather i want to set i from the map to ngObject.MainObj.specificFormatObj send it to function also the model string which in this case would be "ngObject.MainObj.specificFormatObj" .
So for 10 lookups i can write a generic code ,where the model name and model value i can send as parameter to function and set it there, the above way am doing is probably hardcoding values which i want to set to model in a specific format.
Since you need to pass the model name as a parameter, pass it as a string like this from html :
ng-change="genericSetLookups('ngObject.SomeObject.abc',ngObject.SomeObject.abc)"
And in the controller as the model name contains "." we cannot use the name directly as the key. We need to parse the model name. I have cooked something up after searching a bit. Hope it works.
Controller code:
$scope.genericSetLookups(modelName, value){
Object.setValueByString($scope, modelName, value);
}
Object.setValueByString = function(o, s, val) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
if(i != n-1){
o = o[k];
}
else{
o[k] = val;
}
} else {
return;
}
}
return o;
}
Credit must also go to #Alnitak for the answer here
I didn't really understand your problem and the comments didn't make it clearer for me. What I tried to do is give you an example of how I would handle a select box and the model.
I would loop over the options with ng-options and show the selected option by putting {{selected.name}} in the template. Ofcourse if you would want to format the selected value in anyway or react to a change you can use ng-change.
Hope it helps.
Here is my JSFiddle
I'm not sure if I understood your question. If you want to save in your model the value code + name, maybe this code can help you:
<select ng-model="ngObject.MainObj.specificFormatObj" ng-options="(ppm.code + '-' + ppm.name) as ppm.name for ppm in populateMap">
</select>
jsfiddle

How to replace ' / ' with '-' inside ObservableArray ? Knockout js

Well i am trying to pass an observable array via ajax call to my controller but i get every value there except date . i get something like '01-01-01' etc .
I found the issue but unable to fix that as i dont know how to replace / with - .
My ObservableArray have around 10 list items each list item holds a many properties out of those startDate holds the date like ("23/10/2014") . i just need something like ("23-10-2014") .
Tought of posting my function's and more i hope thats not required in this case i believe .
Let me explain with bit of code and sample data :
function myarray()
{
var self=this;
self.startDate=ko.observable("");
self.name=ko.observable("");
self.place=ko.observable("");
}
MyObservableArray :
self.Main= ko.observableArray();
In between i do some stuff to load Data into self.Main and i am sending self.Main to controller having data like below :
self.Main[0] holds :
startDate() -->gives you "23/10/2014" //individual observables inside onservable array
name() --> "jhon"
place()--> "croatia"
Likely
self.Main[9] holds :
startDate() --> "29/05/2012"
name() --> "pop"
place()--> "usa"
I am trying like i want to alter the self.Main() and replace the startDate and use the same self.Main to send to my controller . Once after replacing in self.Main when i check date the / should be replaced with - .
Possible solution : i can use a different observable array and push all the VM's of Main into it but i am trying to do on self.Main without using other .
If someone can show some light it is much appreciated .
What I got that you are facing problem in escaping / in replace.
Try this
"(23/10/2014)".replace(/\//g,"-") //returns "(23-10-2014)"
I tried something for you using simple JS
var arr = [{date:"(23/10/2014)"},{date:"(23/10/2014)"},{date:"(23/10/2014)"},{date:"(23/10/2014)"}];
arr.forEach(function(obj){obj.date = obj.date.replace(/\//g,"-")});
console.log(arr) //will print date field as "(23-10-2014)" for all objects.
One solution would be to add a computed value that returns the array with the right values.
self.Main = ko.observableArray([...values here...]);
self.MainComputed = ko.computed(function() {
var computedArray = [];
self.Main().forEach(function(item) {
var newItem = myarray(); //Create a new item.
newItem.name(item.name());
newItem.place(item.place());
newItem.startDate(item.startDate().replace(/\//g,"-"));
computedArray.push(newItem);
});
return computedArray;
});
Then use the computed value in the places where you need the values with -.
I can think of two other ways to solve your issue, when taken into account that you want to use self.Main:
Replace the / with - before setting startDate on your item.
Change startDate to a computed value while storing the original value in another variable.
The first solution should be pretty straight forward (provided that it is a valid solution).
The second solution would look something like this:
function myarray()
{
var self=this;
self.originalStartDate = ko.observable("");
self.name = ko.observable("");
self.place = ko.observable("");
self.startDate = ko.computed(function() {
if(self.originalStartDate()) {
//We can only replace if the value is set.
return self.originalStartDate().replace(/\//g,"-");
}
else {
//If replace was not possible, we return the value as is.
return self.originalStartDate();
}
});
}
Now when you set the values you do something like:
var item = myarray();
item.originalStartDate = "01/01/2014";
Then when you get the value of startDate you would get "01-01-2014".
I haven't used Knockout.js but you can do this with a Javascript replace:
var str = [your array value] ;
var res = str.replace("/", "-");
For more information:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

extract single variable from JSON array

I hope my question is not as stupid as I think it is...
I want to extract (the value of) a single variable from an JSONarray. I have this jquery code
$(document).ready(function(){
$("#gb_form").submit(function(e){
e.preventDefault();
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
if(data !== false) {
var entry = data;
$('.entries').prepend(entry);
}
});
});
});
the content of data looks like this ("MyMessage" and "MyName" are values written in a simple form from user):
[{"message":"MyMessage","name":"MyName"}]
the var "entry" should give (more or less) following output at the end:
"Send from -MyName- : -MyMessage-"
I'm not able to extract the single array values from data. I tried things like that:
var message = data['message'];
var name = data['name']
var entry = "Send from" + name + ":" +message;
but that gives "Send from undefined: undefined"
Hope you can help me with that.
you can do like this to get first item of array:
var msg = "Send from"+data[0].name + " "+data[0].message;
console.log(msg );
SAMPLE FIDDLE
UPDATE:
as you are using $.post you will need to explicitly parse response as json:
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
var response = jQuery.parseJSON(data);
var msg = "Send from"+response [0].name + " "+response [0].message;
console.log(msg );
});
To access an array you use the [] notation
To access an object you use the . notation
So in case of [{JSON_OBJECT}, {JSON_OBJECT}]
if we have the above array of JSON objects in a variable called data, you will first need to access a particular Json Object in the array:
data[0] // First JSON Object in array
data[1] // Second JSON Object in array.. and so on
Then to access the properties of the JSON Object we need to do it like so:
data[0].name // Will return the value of the `name` property from the first JSON Object inside the data array
data[1].name // Will return the value of the `name` property from the second JSON Object inside the data array

Ways to pass values into Javascript options objects using ASP

Options objects (so called) are used to collect static parameters from the page for a javascript file to operate on. What are the best ways to pass dynamic values from the page into a javascript options object?
Eg how should you insert a value for MyAlbumID in the following
MyOptionsObject({
flashvars: {
xmlFilePath: "http://myurl.com/images.php?album=" + MyAlbumID
})​
Where MyAlbumID is obtained from:
var albumspan = document.getElementById("lblMyAlbum");
var albumtextnode = albumspan.firstChild;
var MyAlbumID = albumtextnode.data;
What exactly is the problem?
onDynamicAction(function(){
// ensure that the DOM is loaded when that action happens
var myAlbumID = document.getElementById("lblMyAlbum").firstChild.data;
// lets hope there is an element with that id and a textnode,
// so that this threw no error
MyOptionsObject ({
flashvars: {
xmlFilePath: "http://myurl.com/images.php?album=" + myAlbumID
} // missing bracket, btw.
});
// set a new object
})

Categories

Resources