include asp.net filled javascript file - c#

I have a javascript file (marker.js) which contains a json variable :
var markers = [
['Service1', 46.81865, -71.31838367115952],
['Service2', 46.81248956788163, -71.29209432884048],
['Service3', 46.80349635182245, -71.26580498652137],
['Service4', 46.81248956788163, -71.39725169811672],
['Service5', 46.821482783940814, -71.40138736927624]
]
In the main javascript, I insert this javascript file so main function can use it. => OK
Now, I want to fill dynamically this var so the coordinates are dynamically get from the database and inserted in the file. Of course, this file should not be written on the disk as an other user would need the same file but with different coordinates.
I think I should tell the server this js file should be interpreted by the asp engine and data retrieved in the codebehind then sent to the "js interface" but how do I do that?
I would appreciate an example of both a home page and the js.
Thank you for your help!

I would return JSON from the controller and include a method in the include file that accepts JSON like so:
function someFunction(json){
var jsonObj = JSON.parse(json);//object is built from json returned by the controller
}
You can call this controller method using AJAX when the main view loads and pass in the JSON from the ajax call

Related

How to return a JSON endpoint in Vue using axios

I'm creating a web application using VueJS, C# and Entity Framework, but there is a problem. I don't know how to return a JSON using Axios to backend. In this project I'm using dynamic forms based on JSON schema and what I'm trying to do is when the user has completed the required fields, once he clicks on the 'send' button, that generated JSON should be redirected to my database where it should parse into a table with it's values.
Here is the function that "should" return the completed JSON but no success
returnJSON(){
axios
.post('http://localhost/jsonSchema/email.json')
.then(response => (this.info = response))
}
I'm not allowed to share more code, but i can provide a link from where I took the JSON schema:
https://github.com/koumoul-dev/vuetify-jsonschema-form. I've tried json server as well, but no success, because once I change those fields into objects, the schema is not working anymore.
I have two questions:
How can I return a link that contains the resulted JSON?
Should I look at this problem from another point of view? Is it better to parse JSON first in C# then send that data to database instead of sending just an endpoint to be parsed directly into a stored procedure?
Basically, the json schema does not affect how you send data back to the backend server, it just enforces that the data (form data in this case) follows a certain structure. Therefor:
Simply look at your form v-model:
<v-jsf v-model="model" :schema="schema" :options="options" />
...which is model in this case. This variable holds your data. Now send it to the server in your submit method:
async returnJSON(){
this.info = await this.$axios.post('<YOUR SERVER URL>', this.model).then(response => response.data)
}
Note that I changed your returnJSON method to use async/await syntax, which is far more understandable here and also made it use response.data aswell as called axios in the way I suspect you need to call it (depending on your setup).

Cannot figure out how this jQuery code is working

So there is a camera taking images every couple seconds and storing those new images with new files names on the server. When a request is made to "mypage", server side the latest images are loaded up and returned in the response. The images subsequently being refreshed with this jQuery code:
(function($) {
$(function() {
var refreshInterval = 5; // Number of seconds between image refreshes
$('#deskshare-grid img').each(function() {
$(this).data('src', $(this).attr('src'));
});
function refreshImages() {
$.get('?r=' + Math.random(), function(response) {
$('#deskshare-grid img').each(function(index) {
$(this).attr('src', $(response).find('#deskshare-grid img').eq(index).attr('src'));
});
setTimeout(refreshImages, refreshInterval * 1000);
});
}
setTimeout(refreshImages, refreshInterval * 1000);
});
})(jQuery);
The jQuery code I shared works and that is great, I didn't write the code and I want to know how it works.
My mind is stuck on the fact that a request was made for the page, the most recent image was retrieved on the server using C# and those images are included in the response. When a more recent image is created, it has a new file name.
How can jQuery refresh the photo for a file name it does not know client side?
Particularly this part of the code is confusing me:
$.get('?r=' + Math.random(), function(response) {
What is the url request for this $.get? I see the network tab of my F12 tools showing the new image responses but I do not understand how an image with a different file name could be requested with jQuery.
UPDATE
The accepted answer is correct but I wanted to elaborate. This jQuery is requesting the entire page again. The HTML response contains new image urls from the server. jQuery is used to parse the response, get the latest image urls and than update the existing HTML content with those new image urls parsed out of the response. This way there is no page flicker by trying to just refresh the entire page.
It does get request to the same page, Math.random() is to make easier to view each request. When you make a request to ? that is the same page.
What is the url request for this $.get?
The first parameter in the $.get is a relative url. This means that the url it's trying to access will be something along the lines of www.yourdomain.com/whatever?r=.
The "?" indicates the start of a query string, the "r" is the start of the request variable and whatever follows the equal sign is the query itself. In this particular case the query is just a randomly generated number that is sent up to the server. Without seeing the server-side code it would appear as if the filename is generated on the client and sent up to the server in this manner, and is probably used to name the file then on the server-side then.
The $.get('?r=' + Math.random(), function(response) { could be this two things:
Its changing the URL as a trick to not to get cached content.
Is server side required as dummy or something that we don't really know.
I recommend to look at the request's and response's headers for each 5'' call.

When converts ASP.NET values of ValueProvider?

My project uses ASP.NET MVC.
I´m sending some data via ajax to a controller-action which looks like
{ "data" : { "DATE" : "\/Date(1409097600000)\/", "NAME" : "thomas } }
I use the ValueProvider of the controller to process the data:
var provider = ControllerContext.Controller.ValueProvider;
var value = provider.GetValue("data.DATE");
// value is now already "27.08.2014 00:00:00"
Why?
Where does this part of conversion happens?
Similar question to that :-
The data above is as content type "application/json; charset=utf=8"
Having data as "application/x-www-form-urlencoded; charset=utf=8" ASP.NET is not able to convert the date-values.
_model.DATE=%5C%2FDate(1409097600000)%5C%2F&_model.NAME=thomas
I think I made something wrong concerning the \ and / in the .NET-date-format: \/Date(1409097600000)\/
(I know netwonsoft.json could be an alternative for javascript-serialization, but unfortunately not at the moment)
If you are sending JSON data to the server using an Ajax post, then the content-type header should reflect that fact (Content-Type="application/json; charset=utf=8"), so that the server interprets the data correctly.
Content-Type="application/x-www-form-urlencoded; charset=utf=8", is for submitting data via an HTML form. If you submit your JSON data with this content type header, the browser will url-encode it and produce the string you illustrated:
_model.DATE=%5C%2FDate(1409097600000)%5C%2F&_model.NAME=thomas
The Date() function has no meaning in an HTTP form post (it is a JSON function) which is why the date conversion fails.

How can I inject javascript from C#?

I'm trying to invoke javascript from C# in my project, I want to call a javascript function that I've defined with parameters but I'm stuck on how to do it.
MainPage.xaml has this my:CordovaView that wraps my phonegap project, but I'm a little lost on how to "inject" and run javascript into it.
Has anyone done this? I'm trying to do push messages
I haven't done this with cordova per se, but in general you just need to remember where the code is executing. The C# code is executing on the server, and the javascript is executing on the client, so, you want your C# to emit a value that can be consumed by the client.
The following javascript snippet is based on Razor engine syntax, hopefully it's enough to get you started.
function alertVar(someVal) {
alert("JS, someVal = " + someVal);
}
$(document).ready(function() {
// in this case the server interpolates #Model and returns HTML with the value replaced
// wrap it in quotes so the js engine treats that value as a string
// this method will then fire when the document loads
alertVar("#Model.ServerValueForClient");
});
This is the html that that the server would send to the client after interpolation (assuming that somewhere on the server you set the value #Model.ServerValueForClient = "set by the server";)
$(document).ready(function() {
// in this case the server interpolates #Model and returns HTML with the value replaced
// wrap it in quotes so the js engine treats that value as a string
// this method will then fire when the document loads
alertVar("set by the server");
});
HTH

Call C# function from Javascript in aspx webform and then reload page

Trying to figure out how to call a c# function in a webform. I tried both ajax and windows.location but could just be off on my path. Trying to send it my c# code at SpeakerList.aspx/update and then gonna attach two variables i have in javascript which shouldnt be too bad. But want it to hit the C# function then reload the page so hoping there is just an easy call im missing.
buttons: {
"Save": function () {
var combo = ASPxClientControl.GetControlCollection().GetByName('DropDownList1');
var value = combo.GetSelectedItem().value;
var billID = $("#billID").val();
window.location = "SpeakerList.aspx/updateRec";
}
You might want to try using WebMethods:
http://aspalliance.com/1922_PageMethods_In_ASPNET_AJAX.all
This allows you to call a function in your page's code behind using JavaScript.
Assuming you are using MVC, you probably want to return a JSON result. An easy way to consume Json within your client webpage is using JQuery. You can return JSON as as the output of a webpage, but I don't recommend it. Create a separate service point that repesents the JSON method.
It is hard to tell what you are actually trying to accomplish, but the normal usage pattern for a JSON method is the supply the parameters as part of the querystring (which you can refactor with routing if you want). The result is then just a JSON packet.
Personally, I like JSON.Net for server side JSON, but you don't actually need this. Look up JSONMethod for examples, etc. that will show you how to do this.
From the browser client, JQuery has a json method, but I personally recommend using the more generic ajax method a JQuery so you can use the handlers for success, error and completion. E.g.
$.ajax({
url: "http:...",
data: queryparm,
cache:false,
timeout:15000,
success: function(data){
jresult = $.parseJSON(data);
...
},
error:function (xhr, ajaxOptions, thrownError)
{
setErrorMsg("Error getting search results: " + thrownError);
}
});
EDIT -- Actually, I've done this exact same thing with webforms too, code is essentially identically (if you use JSON.Net on the server side). You don't have the routing options to make the urls REST compliant, but as an internal json web service, you probably won't really care about that.
As a webpage (.aspx) page, you can use a "postback" this is the simplest method for a web form. You can always declare some hidden fields to use for data passing if you are not passing back a native "control" value. If you don't know how to do this, you need to read a tutorial on using web forms.

Categories