How to send multiple array in JSON in asp.net mvc? - asp.net-mvc

I have a 3 <tr></tr> in my table. user can edit them and on the save button I send the data to the server.
first is main and other all is child of the main. When someone click on new button a new child is created.
now I am thinking to maintain the information like this
var minf = {};
minf.main = $("#tr" + curSplidId).find('input,select').serialize();
res.each(function(n) {
var i = $(this).find('input,select').serialize();
minf[n] = i;
});
All I am trying to do is getting main object and array of childs in JsonResult, I have tried to use Dictionary for JSON.stringify values.
None of these works.
Someone please help me to get it done. Through my testing I found in a case it's sending me querystring in my minf object (I does Stringify) but I am not sure how to handle it on JSONResult as some kind of dictionary stuff where I can read it through the keys.

suppose you have a 3 tr. the best approach is to use a loop on all the tr and create a object same to the DTO that is using in action and make a list of it.
var MainList=[];
$('tr').each(function(){
var MainDTO={};
MainDTO.Column1=$(this).find('td').html();
MainDTO.Column2=$(this).find('td').html();
MainList.add(MainDTO)
});
and pass this MainList directly to action. no serialise required

I think for converting data to json and read that json on server. I make the whole process hard for JS and server to handle.
I change the strategy to serialize all the element and send it to server. it's work fine.
now if I need to read id then I can parse the id which is 3 and come in comma based values.

Related

What is the difference between new sap.ui.model.odata.ODataModel and read?

I am playing around with a OData service and I am very confused when to use this
var oModel = new sap.ui.model.odata.ODataModel("proxy/http/services.odata.org/V3/(S(k42qhed3hw4zgjxfnhivnmes))/OData/OData.svc");
this.getView().setModel(oModel);
vs
var oModel = new sap.ui.model.odata.ODataModel("odatserviceurl", true);
var productsModel = new JSONModel();
oModel.read("/Products",
null,
null,
false,
function _OnSuccess(oData, response) {
var data = { "ProductCollection" : oData.results };
productsModel.setData(data);
},
function _OnError(error) {
console.log(error);
}
);
this.getView().setModel(productsModel);
I have two working example using both approach but I am not able to figure out why using read method if I can achieve same with first version. Please explain or guide me to the documentation which can clear my confusion.
Ok, lets start with the models:
JSON Model : The JSON model is a client-side model and, therefore, intended for small datasets, which are completely available on the client. The JSON model supports two-way binding. NOTE: no server side call is made on filtering, searching, refresh.
OData Model : The OData model is a server-side model: the dataset is only available on the server and the client only knows the currently visible rows and fields. This also means that sorting and filtering on the client is not possible. For this, the client has to send a request to the server. Meaning searching/filtering calls odata service again.
Now, lets look at scenarios where we will use these models:
Scenario 1: Showing data to user in a list/table/display form. Data manipulation is limited to searching and filtering. Here, I would use oData model directly to controls as only fetching of data is required.( your method 1) (NOTE: One way binding). Remember here all changes require a call to server.
Scenario 2: I have an application which has multiple inputs, user can edit changes, also some fields are calculated and mandatory. All in all, many user changes are done which may be temporary and user might not want to save them. Here, you dont want to send these temporary changes to backend as yet. You way want to manipulate, validate data before sending. Here, we will use JSON Model after reading data from odata model ( your method 2). Store the changes in local JSON model, validate and manipulate them and finally send the data using Odata create/update. Remember here all changes DO NOT require a call to server as data is present in local JSON MODEL.
Let me know if this helps you. :)
EDIT : Additional Information :
As per your comment :
Documentation says oModel.read' trigger get request but new sap.ui.model.odata.ODataModel("proxy/http/services.odata.org‌​/V3/(S(k42qhed3hw4zg‌​jxfnhivnmes))/OData/‌​OData.svc")` does the same thing so why and when to use oModel.read
Here, is where you misunderstood. The code
new sap.ui.model.odata.ODataModel("proxy/http/services.odata.org‌​/V3/(S(k42qhed3hw4zg‌​jxfnhivnmes))/OData/‌​OData.svc") will NOT send a read/get Request. It calls the odata services and fetches the metadata of the service. A service can have multiple entities.
For example: the service :http://services.odata.org/Northwind/Northwind.svc/ has mutiple entity sets such as Categories, Customers, Employees etc. So, when I declare : new sap.ui.model.odata.ODataModel("http://services.odata.org/Northwind/Northwind.svc/") it will fetch the metadata for service (not actual data). Only when you call the desired entity set, it will fetch the data. The Entity set is specified :
When you call the read method ( like you have specified '/Products')
Bind the entity set name directly to control like to List,Table etc ( items='{/Products}' )

Getting a unique object from a indexedDB in Dart

I'm trying to get information from an indexedDB, and I want to get just the object from one store by key, and not all the objects from the database. In some examples of javascript and IndexedDB they use the method get() to get the value depending of the key. In DART there is not such method but there is getObject().
How do I get the value of the object when using getObject(key)?
Thanks a lot in advance!
Actually it has getObject(key) method, take a look here https://api.dartlang.org/apidocs/channels/stable/#dart-dom-indexed_db.ObjectStore#id_getObject
The other way for fetching data is Cursor. Here is a good tutorial https://www.dartlang.org/docs/tutorials/indexeddb/#getting-data
So all needed to do was to create a callback. This is how I got the objects value:
var id = "example";
var trans = _db.transaction('myDB', 'readwrite');
var store = trans.objectStore(_TODOS_STORE);
// Get the value from one object ! and render it
var request = store.getObject(id).then((val){functionFor(val);});
Futures need from callbacks to be able to use their values.

How to traverse an array in reverse direction in dust.js?

Is there any simple solution, or it can be accomplished only by defining a custom helper?
The best solution is probably to have the server send the array in reverse order to begin with. In most cases, the "Dust way" is to have the server send data in the format that it will be presented by Dust. If you don't have control over how the data is sent, though, you will either need a helper, or you can manipulate the data (using JavaScript) before passing it to dust.render.
var data = getData();
var data.arrayToReverse = reverseArray(data.arrayToReverse);
dust.render('myDustTemplate', data, function(err, out) {
// Show the result.
});
You would need to write the getData and reverseArray methods, but this way you could get the reversed array without a helper.

How to encode javascript string for display and post back?

I have an MVC application that is rendering rendering the following javascript on the client:
var rawData = [{"ID":5317,"Code":"12345","Description":"sometext \u003c/= 100"}];
The JSON data is a result of serializing an object using the JavaScriptSerializer and then running the result through the Html.Raw() helper.
This data is then used to load a knockout view model and display a popup on hover. In the popup, only the "sometext" portion of the "Description" property is being shown as the string gets converted to the unencoded version when setting the rawData variable (i.e. \u003c is converted to <).
Also, this data ends up being sent back to the server upon saving of data, and the ASP.NET validation kicks in and fails the request as it detects the "
I've worked around this, temporarily, by adding a computed property to my Knockout View Model like so:
self.DescriptionEncoded = ko.observable('');
self.Description = ko.computed({
read: function() {
return self.DescriptionEncoded ();
},
write: function(value) {
self.DescriptionEncoded($('<div/>').text(value).html());
}
});
In this way I can access the escaped property from my popup and the unescaped value is not sent back to the server when I serialize my viewmodel (using .toJSON()).
Is there a more global way to handle this rather than creating computed properties for every object that may have some text that appear to be a bad request while not compromising on security? I've considered an overload/helper to the serialization routine that would accept a list of properties to apply a Find/Replace I am thinking this will have to be handled on a case by case basis in a manner similar to what I've already done. As for sending the data back to the server, I could override the toJSON() method on my view model and delete the properties that don't need to be sent back, but that won't help me with my popup.
Thoughts?
You can encode using Ajax.JavaScriptStringEncode. You might also get the AntiXSS library and use it for the encoding.
I hope I understood your question well.

How to convert JS array to JSON, before passing that to controller (using AJAX - POST call)

I ve a JS array, comprising multiple JS objects.
I want to convert JS array to JSON type, & pass that to controller (using AJAX - POST call).
So that I can retrieve the values from the Array of Objects, in my controller & save them in DB.
NB: I ve tried using $.stringify(myArry), but its not able to send data to controller in JSON format. Also I cant use $.toJSON(myArray), as I m not allowed to include a new plugin in our solution. :(
Plz suggest me any other idea.
Else if anyone can let me know how to deserelize the array in cotroller, that I ve sent by using $.stringify(myArry), that would also great.
Something like
var result = JavaScriptConvert.DeserializeObject(inputContent, JsonDataType);
Per this post, it looks like you'll have to add another plug-in:
JSON stringify missing from jQuery 1.4.1?
The Google solution looks good: http://code.google.com/p/jquery-json/
Or just use the JSON object from Crockford: https://github.com/douglascrockford/JSON-js

Resources