Dynamic javascript in ASP.Net MVC 3.0+Razor - asp.net-mvc-3

I have a javascript that must generate in runtime.The text of script is generate in controller class :
private string mapString
{
get
{
Locations loc = new Locations();
string appPath = Request.ApplicationPath;
loc.ReadXml(Path.Combine(Request.MapPath(appPath) + "\\App_Data", "Locations.xml"));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < loc.Specfications.Count; i++)
{
sb.Append("var myLatLng" + i.ToString() + "= new google.maps.LatLng(" + loc.Specfications[i].Y.ToString() + "," +
loc.Specfications[i].X.ToString() + ");");
sb.Append(" var beachMarker" + i.ToString() + " = new google.maps.Marker({position: myLatLng" + i.ToString() + ",map: map,icon: image,title:'" + loc.Specfications[i].Title + "'});");
....
...
...
ViewData["MapString"] = mapString;
When I use it in script tag :
<script type="text/javascript">
function initialize() {
#Server.HtmlDecode(ViewData["MapString"].ToString())
}
</script>
It dosen't return a true text and it retruns something like this:
contentString0 = '<table width="100%" style="font-family: tahoma; text-align: right; font
**update : The site didn't show my question correctly ,I want to show "'<" but it show "'<"
but it must return :
contentString0 ='
you see that it convert "'<" to "'<" .
But when I use : #Server.HtmlDecode(ViewData["MapString"].ToString()) out of script tag ,all things is OK.

You may want to do it this way, which I think is going to be more flexible than generating code in your controller :
Controller action :
public JsonResult GetCoords()
{
// your code here - im putting a generic result you may
// need to put some logic here to retrieve your location / locations
var result = new { lon = "51.0000", lat = "23.0000" };
return Json(result, JsonRequestBehavior.AllowGet);
}
in your view add :
<script type="text/javascript">
$(document).ready(function () {
$.getJSON('/YourController/GetCoords', function (jsonData) {
var lon = jsonData.lon;
var lat = jsonData.lat;
yourGoogleMapFunction(lon, lat);
});
});
</script>

Related

How to convert HTML(JSON, Ajax ) into C# WinForm?

I'd like to convert following HTML(json, ajax) Code in C# Winform application.
I'll try it by using JSON.Net, but I'm not familiar with C# WinForm.
I want to binding ajax result value after the user click a button.
How do I this??
html code following that :
Thank you.
// format string
function J2String(object) {
var results = [];
for (var property in object) {
var value = object[property];
if (value != null){
results.push(property.toString() + ': ' + value );
}
}
return '{' + results.join(', ') + '}';
}
// format ajax result data
formatstring = function (text) {
if (arguments.length <= 1) return text;
for (var i = 0; i <= arguments.length - 2; i++) {
text = text.replace(new RegExp("\\{" + i + "\\}", "gi"),
arguments[i + 1]);
}
return text;
}
// return data [ GET method ]
function GetAjaxData(){
RcvData.value = "";
$.ajax({
url:"http://127.0.0.1",
type:"GET",
data: { "REQ": formatstring ("AA^^1000^^^^23^1234567^W1234567890^^00000081") },
dataType: "jsonp",
jsonp: "callback",
success: function(data){
RcvData.value = J2String(data);
}
});
}
<body>
Value : <input type="text" style="width:80%" id="RcvData"><br/>
<form name="tform" method="post">
<input type="button" value="Send" onClick="GetAjaxData()" >
</body>
[ .net framework 4.5 ]
~~~ using ~~ ;
using System.Net;
using System.Net.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
private async void btnTest_Click(object sender, EventArgs e){
string reqData = "AA^^1000^^^^23^1234567^W1234567890^^00000081";
textBox1.Text = await GetAjaxData(reqData);
}
private async Task<string> GetAjaxData(string reqData){
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("http://localhost/?callback=jsonp123456&REQ=" + reqData );
response.EnsureSuccessStatusCode();
byte[] buf = await response.Content.ReadAsByteArrayAsync();
Encoding myEncoding = Encoding.GetEncoding("utf-8");
string data = myEncoding.GetString(buf, 0, buf.Length - 1);
dynamic obj = JsonConvert.DeserializeObject(data );
string _parseData = obj.Code
+ "^" + obj.Name
+ "^" + obj.RespCode
+ "^" + obj.Remark;
var result = await Task.FromResult<string>(_parseData);
return result;
}

Search Box Google Fusion Table/Google API

I have a Google Fusion Table containing a land parcels layer. Each parcel is assigned an ARN number. I am trying to create a search box where one can type in the ARN number and it will select and hopefully zoom to that parcel. I'm new to java script and am unsure as to why my search box is not working. The Fusion table has a 'geometry' column containing the spatial information and 'ARN' column is a 'number' field containing the ARN numbers. Here is my code.
function changeMapl0() {
var searchString = document.getElementById('search-string-l').value.replace(/'/g, "\\'");
layer.setOptions({
query: {
select: 'geometry',
from: 'tableID',
where: "'ARN' CONTAINS IGNORING CASE '" + searchString + "'"
}
});
}
<body>
<div style="margin-top: 10px;">
<label>Enter Roll Number</label><input type="text" id="search-string-l">
<input type="button" onclick="changeMapl0()" value="Search">
</div>
</body>
Any help would be appreciated.
Thanks;
Matt
You would probably want to do something like this, you will have to call a zoom2query function. You will want to probably want to calculate the lat and long of the centroid of parcel for zoom functionality, make sure to call you geometry column column on the map so you don't have the points.
function changeMap() {
var searchString = document.getElementById('search').value.replace("'", "\\'");
if(searchString == "") {
var query="SELECT 'Lat' FROM " + tableid;
}
else {
var query="SELECT 'Lat' FROM " + tableid + " WHERE 'PARCEL_ID' = '" + searchString + "'";
}
// layer.setQuery(query);
if(searchString == "") {
var query="SELECT 'Lat','Long' FROM " + tableid;
}
else {
var query="SELECT 'Lat','Long' FROM " + tableid + " WHERE 'ARN' = '" + searchString + "'";
}
zoom2query(query);
}
var infowindow = new google.maps.InfoWindow();
function zoom2query(query) {
// zoom and center map on query results
//set the query using the parameter
document.getElementById("query").innerHTML = query;
var queryText = encodeURIComponent(query);
var query = new google.visualization.Query('https://www.google.com/fusiontables/gvizdata?tq=' + queryText);
//set the callback function
query.send(zoomTo);
}
function zoomTo(response) {
if (!response) {
alert('no response');
return;
}
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
numRows = response.getDataTable().getNumberOfRows();
numCols = response.getDataTable().getNumberOfColumns();
var lat = response.getDataTable().getValue(0,0);
var lng = response.getDataTable().getValue(0,1);
var zoom_level = 19;
var location = new google.maps.LatLng(lat,lng);
map.setCenter(location);
map.setZoom(zoom_level);
}
Here is an example of what I have done, we have RP numbers but mine zooms to the parcel
https://googledrive.com/host/0B0J_A50xWBAqNHZqVlUxSkNUbWs/Shoshone.html

Parsing JSON with AJAX - show random item of the JSON and update after an amount of time

I'm able to parse JSON with ajax, but at the moment it shows all the names out of the JSON.
I want only one name viewed and after an amount of time I want another one viewed and so on..
Ajax code:
$(document).ready(function(){
parseJson();
});
function parseJson(){
$.ajax({
url : 'data/members.json',
dataType : 'json',
success : function(data) {
succes(data);
},
error: function(){
window.alert("error");
}
});
};
function succes(dataObj){
var counter = 1;
$.each(dataObj.Members.Member, function(indexData, valueData){
var htmlString = "";
htmlString += '<article class="memberInfo" data-object="' + counter + '">';
htmlString += "<div class=''><p>" + valueData.Firstname + ' ' + valueData.Surname + "</p></div>";
htmlString += "</article>";
$("#members").append(htmlString);
counter++;
});
}
Rather than use .append you can use .html and set a staggering timeout so that it cycles through the names that get displayed:
var timer = 0;
$.each(...
setTimeout(function () {
var htmlString = "";
/* snip */
$("#members").html(htmlString);
}, timer + (indexData * 2000));
});

Display image instead of URL

I have developed a ASP.NET MVC application with signalr to display the records on the page.
My table has five columns (jobid [int], name[varchar], lastexecutiondate[datetime],status[int],imageurl[string])
Here is my markup from view page:
<script type="text/javascript">
$(function () {
// Proxy created on the fly
var job = $.connection.jobHub;
// Declare a function on the job hub so the server can invoke it
job.client.displayStatus = function () {
getData();
};
// Start the connection
$.connection.hub.start();
getData();
});
function getData() {
var $tbl = $('#tblJobInfo');
$.ajax({
url: '../api/values',
type: 'GET',
datatype: 'json',
success: function (data) {
if (data.length > 0) {
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th><th>Last Executed Date</th><th>Status</th><th>Image URL</th></tr>');
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].LastExecutionDate.toString().substr(0, 10) + '</td><td>' + data[i].Status + '</td><td>' + data[i].imageurl + '</td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
</script>
</head>
<body>
<div>
<table id="tblJobInfo" style="text-align:center;margin-left:10px">
</table>
</div>
</body>
And below is my code to get the data from database
SqlDependency.Start(connection.ConnectionString);
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new JobInfo()
{
JobID = x.GetInt32(0),
Name = x.GetString(1),
LastExecutionDate = x.GetDateTime(2),
Status = x.GetString(3),
imageurl = x.GetString(4)
}).ToList();
I want to display the image instead of the URL.
You should just need to create an image tag in your JavaScript table row function:
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].LastExecutionDate.toString().substr(0, 10) + '</td><td>' + data[i].Status + '</td><td><img src="' + data[i].imageurl + '"/></td></tr>');
}
I can think of a couple of ways to address your comment below. In code, create a helper function to do this for you:
SqlDependency.Start(connection.ConnectionString);
using (var reader = command.ExecuteReader())
return reader.Cast<IDataRecord>()
.Select(x => new JobInfo()
{
JobID = x.GetInt32(0),
Name = x.GetString(1),
LastExecutionDate = x.GetDateTime(2),
Status = x.GetString(3),
imageurl = GetImageUrl(x.GetString(3))
}).ToList();
private string GetImageUrl(int status){
switch(status){
case 1:
return "some.jpg"
case 2:
return "someother.jpg"
default:
return "blank.jpg"
}
}
I don't know your code that well, so this assumes that your select is not being cast to a SQL statement (it doesn't appear that it is).
To do the same thing client side, you would implement the GetImageUrl function as a JavaScript function and to the same type of thing.
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].JobID + '</td><td>' + data[i].Name + '</td><td>' + data[i].LastExecutionDate.toString().substr(0, 10) + '</td><td>' + data[i].Status + '</td><td><img src="' + GetImageUrl(data[i].Status) + '"/></td></tr>');
}
function GetImageUrl(status){
switch(status){
case 1:
return "some.jpg"
case 2:
return "someother.jpg"
default:
return "blank.jpg"
}
}

changing rally basic dropdown menus after display

I have a rally.sdk.ui.basic.Dropdown menu in a Rally App that I would like to change based on user input. So I will call display() on the dropdown menu, and then later I want to change the contents of that menu.
Has anybody done this? When I try, it crashes. I've also tried calling destroy() on the dropdown menu and then calling display() on a new menu that I allocate, but that crashes as well with an obscure dojo error.
Any suggestions on how to change dropdown menus on the fly?
I've included a very stripped down example below of trying to destroy and then re-display the menu:
<html>
<head>
<title>Incoming Defects by Severity</title>
<meta http-equiv="X-UA-Compatible" content="IE=7" >
<meta name="Name" content="Defects by Severity" />
<script type="text/javascript" src="https://rally1.rallydev.com/apps/1.29/sdk.js"></script>
<script type="text/javascript">
function DefectChart() {
this.display = function() {
var defectVersionDropdown;
var count = 1;
function makeDefectChart(results){
initDefectVersionDropdown();
};
function renderPage() {
var queryConfig = [];
var startDate = '2011-06-06';
var endDate = '2012-02-02';
var queryArray = ['CreatedDate >= "' + startDate + '"', 'CreatedDate <= "' + endDate + '"'];
var versionFilter = defectVersionDropdown ? defectVersionDropdown.getDisplayedValue() : 'ALL';
if (versionFilter != 'ALL') {
queryArray.push('FoundInBuild contains "' + versionFilter + '"');
}
// console.log(queryArray);
queryConfig.push({
type : 'Defects',
key : 'defects',
query: rally.sdk.util.Query.and(queryArray),
fetch: 'Severity,State,LastUpdateDate,CreationDate,OpenedDate,AcceptedDate,LastUpdateDate,ClosedDate,Environment,FoundInBuild'
});
rallyDataSource.findAll(queryConfig, makeDefectChart);
}
function defectVersionChange(sender, eventArgs) {
var version = eventArgs.value;
renderPage();
}
function initDefectVersionDropdown() {
if (defectVersionDropdown != null) {
defectVersionDropdown.destroy();
defectVersionDropdown = null;
}
if (defectVersionDropdown == null) {
console.log('initDefectVersionDropdown');
count++;
var menuItems = [{label: "ALL", value: "ALL"}];
for (var i=0; i < count; i++) {
menuItems.push({label: count, value: count});
}
var config = {
label: "Found In Version:",
items: menuItems
};
defectVersionDropdown = new rally.sdk.ui.basic.Dropdown(config);
defectVersionDropdown.addEventListener("onChange", defectVersionChange);
defectVersionDropdown.display("defectVersionDiv");
}
}
var workspaceOid = '__WORKSPACE_OID__'; if (workspaceOid.toString().match(/__/)) { workspaceOid = XXX; }
var projectOid = '__PROJECT_OID__'; if (projectOid.toString().match(/__/)) { projectOid = XXX; }
rallyDataSource = new rally.sdk.data.RallyDataSource( workspaceOid,
projectOid,
'__PROJECT_SCOPING_UP__',
'__PROJECT_SCOPING_DOWN__');
initDefectVersionDropdown();
renderPage();
}
}
function getDataAndShow() {
var defectChart = new DefectChart();
defectChart.display();
}
function loadRally() {
rally.addOnLoad(getDataAndShow);
}
loadRally();
</script>
</head>
<body>
<div id="defectVersionDiv"></div>
</body>
</html>
Destroying the old one creating and displaying a new one is the correct way to do this. This is a common pattern when developing apps using the App SDK. If you provide a code snipped along with the dojo error you are getting the community can probably be of better assistance.

Resources