Client side processing in asp.net mvc 2.0 - asp.net-mvc

We are looking on an implementation in which data is processed at client side. Need inputs on how to process the data in JSON or any other type at client side in ASP.Net MVC 2.0.
Details: Inputs are accepted from the user and required to be saved in a list (or any other object) at the client side. Once the user actions are complete, the list object is required to be posted back to the server.
This is to avoid round trip to server and once all the data is ready in the list(objects) send it to server for processing
e.g. Accept Item(object) details as item name and item description. For first time add; in the same page store item in the list of object in client side itself. Every time item added, it is saved in list. At the same time list item is displayed on the same page in table format. After adding all the items when user submit data, list of object is posted back.
How can we achieve this in ASP.Net MVC 2.0 in a load balanced environment?
Any pointers would be very helpful

what kind of a list are you refering to here? like a bunch of check boxes? and in what format do you want to send the data to your server?
If you're using a bunch of checkboxes just post that data from the form straight to your action. I would suggest you just keep them in an array in javascript or add the values separated by a char like '|' or a ',' in a hidden text field and separate the items on the server side.

ASP.NET MVC 2 ships with the jQuery library, which you could use to perform this rough example...
var dataItems = new Array();
function AddDataItem(myDataItem) {
dataItems[dataItems.length] = myDataItem;
}
function SendDataItems() {
var data = "{";
for (var i = 0; i < dataItems.length; i++) {
data += ' question' + i + ': "' + dataItems[i] + '",';
}
// Remove the trailing comma:
data = data.substring(0, data.length-1) + "}";
$.ajax({
type: 'POST',
url: 'YourPage.html',
data: data,
success: function(response) {
alert(response);
},
dataType: "json"
});
}

Related

Data Gets Converted when passed to CREATE_STREAM

I have created an UI5 Application to read a file and send it to a custom OData Service in the Backend.
onUploadFile: function() {
var oFileUpload =
this.getView().byId("fileUploaderFS");
var domRef = oFileUpload.getFocusDomRef();
var file = domRef.files[0];
var that = this;
var reader = new FileReader();
var ftype = file.type;
reader.readAsArrayBuffer(file);
reader.onload = function(evt) {
var vContent = evt.currentTarget.result
console.log(vContent);
var hex = that.buf2hex(vContent);
that.updateFile(hex, ftype);
}
},
buf2hex: function(buffer) {
return [...new Uint8Array(buffer)]
.map(x => x.toString(16).padStart(2, '0'))
.join('');
}
When I print the content of hex on the console before sending it to the backend, the data starts with 89504e470d0a1a0a0000000d49484 ....
Even before sending the data in the payload to Odata Service it shows the correct data
Here is the Odata Service
Inside the Create Stream the data when received, is getting converted into something else. As a result the image that has been saved is not opening.
I tried to change the Data Type of Content in SEGW to Binary and it did not work. I also tried to convert the data in the create_stream but in vain. At last I tried reading the data in UI5 in different formats but of no use.
This whole Odata service works perfectly fine when I load the data through Postman Application.
Please help me resolve this Issue. Thanks In Advance.
The sap.ui.unified.FileUploader has everything built in. No need for conversions from Buffer to hex.
Make sure that your FileUploader knows where to upload the file
<unified:FileUploader xmlns:unified="sap.ui.unified"
id="fileUploaderFS"
uploadUrl="/sap/opu/odata/sap/Z_TEST_SRV/FileSet"
/>
The attribute uploadUrl points to the media entity for which you implemented the create_stream method.
Then when the upload is triggered via button press, simply get the FileUploader, set the token (for security reasons when doing a POST request), and fire the upload method.
onUploadFile: function () {
const oFileUpload = this.getView().byId("fileUploaderFS");
const sToken = this.getModel("nameOfTheModel").getSecurityToken();
const oTokenParam = new FileUploaderParameter({
name: "x-csrf-token",
value: sToken
});
oFileUpload.removeAllHeaderParameters()
oFileUpload.addHeaderParameter(oTokenParam);
oFileUpload.upload();
}
To use FileUploaderParameter, make sure to import it at the beginning:
sap.ui.define([
// ...,
"sap/ui/unified/FileUploaderParameter"
], function (/*..., */FileUploaderParameter) {
// ...
Now about your File entity. When working with it via create_stream or read_stream, you don't use the entity structure but is_media_resource. This means your entity doesn't need a property content. Or most of the other properties (except a unique id and the mime type). All other properties would only be used if you want to do one of the CRUD methods (which happens almost never when dealing with streams).

Rails Frontend Trying to save autogenerated data to database without form

I'm new to ruby on rails. I'm trying to save data that is generated by itself to the database. i have looked into and found I was meant to use ajax, however all the videos/forums i have seen are example of ajax that use form and not refreshing page. i want to save data automatically without pressing submit.
Assume that the project is fresh project with postgresql as the database. I have created a database that can hold geo points by using postgis. i have created another page where it has map implemented where i can manully pin location. I want to save the manuuly pinned location to the database.
function onMapClick(e) {
alert("You clicked the map at " + e.latlng);
}
mymap.on('click', onMapClick);
var popup = L.popup();
function onMapClick(e) {
popup
.setLatLng(e.latlng)
.setContent("You clicked the map at " + e.latlng.toString())
.openOn(mymap);
}
mymap.on('click', onMapClick);
The e.latlng holds the geopoint, but i dont know how to save it the database if the user clicks anywhere on the map.
You don't need submit form to use ajax.
Basically what you want is add event listener to the map, and when user click then send ajax request to the controller.
For example, let's say that your map is inside div with id my-map.
If you use jQuery you can write something like this:
$('#my-map').on('click', function() {
# add your logic here
$.ajax({
url: 'your-url',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
'let': data you want to send to backend
})
}
Hope it works!
EDIT:
After I looked your code I found that you can not have jQuery in your project so you can not use jQuery ajax. You need use vanilla javascript. So instead this snippet above, you can write this.
var xhttp = new XMLHttpRequest();
const params = { saving_location: { geoPoints: e.latlng } }
xhttp.onreadystatechange = function() {//Call a function when the state changes.
if(xhttp.readyState == 4 && xhttp.status == 200) {
alert(http.responseText);
}
}
xhttp.open("POST", "/saving_locations", true);
xhttp.setRequestHeader('Content-Type', 'application/json', 'Accept', 'application/json');
xhttp.send(JSON.stringify(params));
Also add protect_from_forgery with: :null_session in your application controller and skip_before_action :verify_authenticity_token in your Saving Location controller.(under before_action).
Here is good blog post why you need this https://blog.nvisium.com/understanding-protectfromforgery
Please notice that you wan't save your database, because your geoPoints type in database is type of point and you send string to rails controller. I never work with points in rails so I can not help you here.(You can always add two columns in db, one for longitude and one for latitude and then store numbers instead point)

ajax post to external database from Rails app

I am trying to insert data from a form built with Ruby on Rails to my SQL Server database. I have connected my database correctly and can pull data from it. I am now trying to post back to it. I am needing help with figuring out how to get the data from the form into the correct columns in my table in the database.
My ajax:
<script>
$('#Favorites').on('submit',function(event){
    var $form = $(this),
    data = $form.serialize();
    var url = 'http://localhost:3000/welcome/insert';
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: function(){
            
alert('Your form has been successfully submitted!');
document.getElementById('Favorites').reset();
window.location.reload();
        },
        fail:function(){
            alert('something went wrong...try again');
        }
    });
return false;
});
</script>
My controller function:
def insert
#ipinsert=Ipdw.connection.execute("insert into [DB_Test02].[dbo].[My_Table] (Report_Name,Report_Link)
values ('I am cool','www.google.com')")
end
Currently I just have a dummy insert statement here to make sure that I can insert into the tables and I can. I just need to know how to break out the form values sent to the controller and how to tell Rails what table and columns to put those values into.
Rails will format the data for you. In controller like this:
{'Report_Name': 'some name', 'Report_link': 'www.example.com'}
and will be accessible via the params.
Your job is now to format the data correctly for the manual execution of the SQL query.
insert_values = "('%s', '%s')" % params['Report_Name'], params['Report_link']
#ipinsert=Ipdw.connection.execute("insert into [DB_Test02].[dbo].[My_Table] (Report_Name,Report_Link) values #{insert_values}")
For the problem of which table to add to your DB server you could specify this in hidden fields in your form and every fieled should have a name, When you say $form.serialize(); it turns it to something like FirstName=Amr&SecondName=Adel and so on where FirstName is the name of the field and Amr is the value of the field, Then you put this serialization into a form of JSON format like {"data": $form.serialize()} and add dataType: "JSON" to your post request, In your Insert function you can get it through params[:data] and split it with& to be something like ['FirstName=Amr','SecondName=Adel'] and every element split it with = so you can get something like this [['FirstName','Amr'], ['SecondName','Adel']].
Hope this helps.

Unable to post files using ajax post

We use ASP.Net Mvc 4.0.
My objecctive is to save a form with both normal input fields as well as file input fields.
I should be able to add extra data while posting.
I should be able to do perform few actions on 'Ajax Post's Success.
We used ajax post to post the form data as we could accomplish above 2, but failed in serializing and posting of files to server.
Whenever we post using ajax post, always Request.Files.Count == 0, when i check in my controller's Post Action.
ajax post i have used is:
function PostData(formId, eventSource, eventName, eventArgs, controlId) {
var $dialogForm = $("#" + formId + "Form");
fdata = $dialogForm.serialize();
fdata = fdata + '&eventSource=' + eventSource + "&eventName=" + eventName + '&eventArgs=' + eventArgs;
$.ajax({
url: $dialogForm.attr("action"),
type: $dialogForm.attr("method"),
cache: false,
data: fdata,
success: function (result) {
ProcessEvent(result);
}
});
}
Please provide me a solution for this!
well you cannot upload files when you go with the concept of ajax. But there are tweaks which are used to upload file and form data using ajax. Whenever a file type is encountered in a form the form data along with file can be copied to an iframe and the iframe can be submitted which give you a feel that file has been uploaded along with other form data using ajax.
There are various plugin available in jquery which ease this task for you.
One of my favourite is ajax form
http://malsup.com/jquery/form/#file-upload
You can use this one..

jQuery Dialog posting of form fields

I'm trying to do some data entry via a jQuery modal Dialog. I was hoping to use something like the following to gather up my data for posting.
data = $('#myDialog').serialize();
However this results in nothing. If I reference just the containing form instead myDialog then I get all the fields on the page except those within my dialog.
What's the best way to gather up form fields within a dialog for an AJAX submission?
The reason this is happening is that dialog is actually removing your elements and adding them at root level in the document body. This is done so that the dialog script can be confident in its positioning (to be sure that the data being dialog'd isn't contained, say, in a relatively positioned element). This means that your fields are in fact no longer contained in your form.
You can still get their values through accessing the individual fields by id (or anything like it), but if you want to use a handy serialize function, you're going to need to have a form within the dialog.
I've just run into exactly the same problem and since I had too many fields in my dialog to reference them individually, what I did was wrap the dialog into a temporary form, serialize it and append the result to my original form's serialized data before doing the ajax call:
function getDialogData(dialogId) {
var tempForm = document.createElement("form");
tempForm.id = "tempForm";
tempForm.innerHTML = $(dialogId).html();
document.appendChild(tempForm);
var dialogData = $("#tempForm").serialize();
document.removeChild(tempForm);
return dialogData;
}
function submitForm() {
var data = $("#MyForm").serialize();
var dialogData = getDialogData("#MyDialog");
data += "&" + dialogData;
$.ajax({
url: "MyPage.aspx",
type: "POST",
data: data,
dataType: "html",
success: function(html) {
MyCallback(html);
}
});
}
Form element inside dialog is removed from form and moved to the end of the body. You need something like this.
$("#dialog_id").dialog().parent().appendTo($("#form_id"));
jQuery("#test").dialog({
autoResize:true,
width:500,
height:600,
modal: true,
bgiframe: true,
}).parent().appendTo("form");
This works like charm

Resources