How to use a server side variable in javascript with Razor - javascript

I have a piece of code in a view as
#if (Model.Count() > 0)
{
var locations = new List<string>();
var count = 1;
foreach (var shop in Model)
{
locations.Add(string.Format(
#"{{
title: ""Shop Name: {0}"",
position: new google.maps.LatLng({1}, {2}),
icon: ""{3}""
}}",
shop.ShopName,
shop.Location.Latitude,
shop.Location.Longitude,
count
)
);
count++;
}
var locationsJson = "[" + string.Join(",", locations.ToArray()) + "]";
}
How can I assign the locationsJson to a javascript variable as
<script type="text/javascript">
var jsLocations = #locationsJson;
</script>

Perform your embedded server code ON the server side instead, and then you could make it a property of the model and do something like:
<script type="text/javascript">
var jsLocations = #Model.locationsJson;
</script>

I have a piece of code in a view as
You absolutely should never have such piece of code in your view. Try this (shorter, better, safer):
<script type="text/javascript">
var jsLocations = #Html.Raw(Json.Encode(Model));
$.each(jsLocations, function(index, item) {
// TODO: do something with the item, for example
// alert(item.ShopName); or alert(Location.Latitude);
});
</script>

Your code will work fine.
However, you need to escape the values in your JSON, or you'll have an XSS hole.
You should use a real JSON serializer.

Related

How do I pass an array from a controller into blade in laravel using javascript

I am trying to pass an array to javascript in view Laravel, I tried several answers I found on the internet but it doesn't work. Here's my controller code:
$data=DB::table("tb_trx_perhitungan_bunga_simpanan")
->selectRaw('trx_bulan')
->get();
return view('crud.form.cobaNampilin',compact('data'));
and then this is my javacript and jquery in blade view
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var a;
var array = {{!! json_encode($data) !!}};
var i;
var b;
$('#bulan').keyup(function(){
var bayar=parseInt($('#bulan').val());
for(a=0;a<=array;a++){
if(bayar==array[a]){
i=1;
}
else{
i=0;
}
}
$('#hasil').val(i);
});
});
</script>

How can I read my html file inside JavaScript file using AJAX?

This is my html code. Here I declared one variable.
<script src="index.js">
var str = {{:stringVar:}};
</script>
This is my JavaScript file content. Here if my condition satisfies my HTML file variable have to get my javascript file variable and it must be replaced.
var hello='gettingvalue from browser'
if(hello ='master'){
var changestr ='new asp key for mas';
}
else{
var changestr ='new asp key for dev'
}
How can I get my HTML file variable into js file?
you can use ajax to read your HTML file.
first read your HTML file then replace your new variable then write it into html file
Here I gave code to read html file inside JS file and replace that variable
if(true){
var aspkey = 'key for master';
var ajax = new ej.base.Ajax('./src/template.html', 'GET', true);
ajax.send().then(function (result) {
var f = result;
var newstr = f.replace(/{{:stringVar:}}/, aspkey)
});
}
else{
var aspkey = 'key for dev';
var ajax = new ej.base.Ajax('./src/template.html', 'GET', true);
ajax.send().then(function (result) {
var f = result;
var newstr = f.replace(/{{:stringVar:}}/, aspkey)
});
}
Finally you have to write this into your HTML file
You could get HTML file content using jquery ajax call as follows
$.get("PATH_TO_HTML_FILE", function(fileText){
console.log(fileText)
});

get json api data to display correct

Question, why and how do i get my json api data to display. to display my api infomation
I am new to api and am trying
json data
[{"title":"One article - API 1 - 2017-04-25 15:43:20"},{"title":"Another article - API 1 - 2017-04-25 15:43:20"},{"title":"Great article - API 1 - 2017-04-25 15:43:20"}]
I have a small js file that im using to get my api
$(document).ready(function () {
$('#get-data').click(function () {
var showData = $('#show-data');
$.getJSON('https://some api ', function (data) {
console.log(data);
var items = data.title (function (item) {
return title;
});
showData.empty();
if (items.length) {
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
showData.text('Loading the JSON file.');
});
});
I then have a html part to display the api info onlick
<body>
Get JSON data
<div id="show-data"></div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="example.js"></script>
</body>
You need to iterate over the items in data to build your HTML and then append it to the showData div.
I also changed how you are building your <li> a little bit for security purposes. If you set the HTML of the <li> equal to each item's title property coming back from data, and the title contains malicious HTML/scripts, your application has been successfully compromised with an XSS attack.
As a general rule of thumb, never set HTML unless you absolutely have to - especially if it is coming from a third-party source.
$(document).ready(function() {
$('#get-data').click(function() {
var showData = $('#show-data');
$.getJSON('https://some api ', function(data) {
showData.empty();
var items = data.map(function(elem) {
return $("<li />", {
text: elem.title
});
});
var list = $('<ul />').append(items);
showData.append(list);
});
});
});
Get JSON data
<div id="show-data"></div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="example.js"></script>
There is no method data.title() you want Array#map()
Scaled down version:
$.getJSON('https://some api ', function(data) {
// map title properties into flattened array
var items = data.map(function(item) {
return item.title;
});
if (items.length) {
var content = '<li>' + items.join('</li><li>') + '</li>';
var list = $('<ul />').html(content);
showData.append(list);
}
});
DEMO
The data returned in $.getJSON is a collection of objects. That might have been clear to you while you consoled the response.
Now, loop through data and you can access each object and insert title into li.
See a sample code below:
data.map(function(obj) {
console.log(obj.title) // use this in your <li>
})

JSON file (Extracting data)

I have the following data in a JSON file (pio2.json)
{
"controles":[{
"chart":[{
"type":"columns",
"title":"Pollitos"
}],
"datos":[{"key":"Math","value":98},
{"key":"Physics","value":78},
{"key":"Biology","value":70},
{"key":"Chemistry","value":90},
{"key":"Literature","value":79}
]
}]
}
I need to extract data in array for a chart from "datos" for my html / javascript
$(function () {
var processed_json = new Array();
$.getJSON('pio2.json', function(data)
{
// Populate series
for (i = 0; i < data.controles.length; i++){
processed_json.push(data.controles[i].chart);
}
}
}
Any advice?
not sure what your issue is. I should be serialized server side and deserialized client side. When deserialized, it will be in an array.
I copied your data, as is, into json1.json pasted in your code and made some minor changes and it worked fine. I got the results out of the json page into my html page.
<body>
<script type="text/javascript">
$(document).ready(function () {
var processed_json = new Array();
$.getJSON('json1.json', function(data)
{
// Populate series
for (i = 0; i < data.controles.length; i++){
processed_json.push(data.controles[i].chart);
}
})
});
</script>
</body>

How to execute JavaScript function on PartialView load in MVC 3

\\code
public ActionResult mapPartial(DataTable dt)
{
string strEvents = "[";
foreach (DataRow row in dt.Rows)
{
strEvents += "[" + row["Lat"].ToString() + ", " + row["Long"].ToString() + ", " + "\"" +
row["LastName"].ToString() + row["DateOfBirth"].ToString() + "\"" + "],";
}
strEvents = strEvents.Remove(strEvents.LastIndexOf(","));
strEvents += "]";
ViewBag.locpoints = strEvents;
return PartialView(dt);
}
//in the partial view page
<script type="text/javascript">
function mapInit(Viewbag.locpoints) {
var arr = $.parseJSON(Viewbag.locpoints);
//more code which assigns a map to div map below
}
</script>
<div id="map" class="map"></div>
How can i call the JS function immediately to render my map when the partial view is loaded. The partial method in the controller returns a string which is used as parameter in the JS function. Hope it makes sense.
Since you appear to be using JQuery why not:
<script type="text/javascript">
$(document).ready(function(){
var arr = $.parseJSON("#Viewbag.locpoints");
//more code which assigns a map to div map below
});
</script>
I also changed how you referenced your ViewBag value since the way you have it, it won't be be a string literal in JavaScript.
Also, as a side note consider using JSON serializer to convert your data into JSON. It is considered a bad practice to do it manually like you did above.
After you define it, you just call it. However, it looks like you are including the MVC Viewbag values in the JS function definition. You should be passing those values when you call the JS method:
<script type="text/javascript">
function mapInit(locPoints) {
var arr = $.parseJSON(locPoints);
//more code which assigns a map to div map below
}
mapInit(#(Viewbag.locpoints));
</script>
Note: This assumes you have jQuery loaded.
Consider using the onSuccess Ajax Option and wire up a javascript function where your jquery is written. For example you have following script written in your mainView that calls the partial View. Suppose you want do something when the anchor tag in your partial view is clicked
var fromPartial=function()
{
var v = $(this).closest("div");
var mId = v.attr('id');
if (mId == 'divDetail') {
event.preventDefault();
//what you want to achieve
}
}
Now in your partial view the anchor tag is created as shown below
#Ajax.ActionLink("Select", "AssignSpeaker", new {
conferenceId = ViewBag.ConferenceId, sessionId = session.Id },
new AjaxOptions() { HttpMethod="Get",
InsertionMode= InsertionMode.Replace, UpdateTargetId="yourTarget",
OnSuccess="fromPartial" })
We have implemented a much simpler solution.
_Layout.cshtml after #RenderSection("scripts", required: false) (and Jquery,etc.)
<script>
$(document).ready(function () { if (typeof partialScript !== "undefined") partialScript();});
</script>
Then, in your partial view:
<script type="text/javascript">
function partialScript() {
alert("hi");
}
</script>
This ensures the following:
jQuery is loaded
All main view scripts are loaded
DOM is ready
Try to call your controller via JQuery.
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'your_controller_url',
success: function (data) {
//Do your stuffs here
}
});
}
The only way you can do this is by calling your controller action using JQuery and have it return your partial view. Use Jquery to update whatever section of the page the partial view goes to and then call the javascript method you want to render the map

Categories

Resources