How to save coordinates from with openlayers ASP.NET - c#

I want to save my coordinates from the frontend to the backend and I don't know how to send them.
the coordinates are saved in a JS array and I don't know how to transfer them to C#.
HTML, CSS & JS for the map
<link rel="stylesheet" href="~/css/ol.css">
<link rel="stylesheet" href="~/css/ol-ext.css">
<script src="~/js/ol.js"></script>
<script src="~/js/ol-ext.js"></script>
#*<script src="~/js/elm-pep"></script>*#
#*<script src="~/js/JavaScript.js"></script>*#
<div id="map" style="width:600px; height:400px;">
<div class="photon ol-search ol-unselectable ol-control ol-collapsed">
<input asp-for="coordinates" type="search" class="search" autocomplete="off" placeholder="Search...">
<input asp-for="coordinates" type="button" class="ol-revers" title="click on the map">
<ul class="autocomplete history">
<li data-search="0"> 398<i> 9350004 Jérusalem (Israël)</i></li>
<li class="copy">© OpenStreetMap contributors</li>
</ul>
</div>
</div>
<div class="button-70" style="z-index:1;" id="location-button">
#*<button id="location-button" title="Get your location"></button>*#
#*<button asp-for="coordinates" class="button-70" id="location-button" role="button" title="Get your current location">📍 Get cuttent location</button>*#
<input asp-for="coordinates" type="button" value="📍 Get cuttent location" id="location-button" />
</div>
<style>
.button-70 #location-button {
background: none;
border: none;
transform: scale(2)
}
.button-70 {
transform: scale(0.7);
background-image: linear-gradient(#0dccea, #0d70ea);
border: 0;
border-radius: 4px;
box-shadow: rgba(0, 0, 0, .3) 0 5px 15px;
box-sizing: border-box;
color: #fff;
cursor: pointer;
font-family: Montserrat,sans-serif;
font-size: .9em;
margin: 5px;
padding: 10px 15px;
text-align: center;
user-select: none;
-webkit-user-select: none;
touch-action: manipulation;
}
</style>
<script type="text/javascript">
var layers = [new ol.layer.Tile({ source: new ol.source.OSM() })];
var map = new ol.Map({
target: 'map',
view: new ol.View({
zoom: 5,
center: [166326, 5992663]
}),
interactions: ol.interaction.defaults({ altShiftDragRotate: false, pinchRotate: false }),
layers: layers
});
var search = new ol.control.SearchPhoton({
lang: "fr",
reverse: true,
position: true
});
map.addControl(search);
var markers;
search.on('select', function (e) {
map.getView().animate({
center: e.coordinate,
zoom: Math.max(map.getView().getZoom(), 16)
});
loc(e.coordinate);
});
function loc(e) {
console.log(e);
if (markers) {
map.removeLayer(markers)
}
markers = new ol.layer.Vector({
source: new ol.source.Vector(),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'https://ucarecdn.com/4b516de9-d43d-4b75-9f0f-ab0916bd85eb/marker.png' // => https://app.uploadcare.com/projects/c05bbeb5e1a61e862903/files/7110cd57-b0ee-4833-bcd1-ff0343dd01cc/?limit=100&ordering=-datetime_uploaded
})
})
});
map.addLayer(markers);
var marker = new ol.Feature(new ol.geom.Point(e));
markers.getSource().addFeature(marker);
}
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
document.querySelector("#location-button").addEventListener("click", function (e) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
console.log(e);
if (markers) {
map.removeLayer(markers)
}
markers = new ol.layer.Vector({
source: new ol.source.Vector(),
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 1],
src: 'https://ucarecdn.com/4b516de9-d43d-4b75-9f0f-ab0916bd85eb/marker.png' // => https://app.uploadcare.com/projects/c05bbeb5e1a61e862903/files/7110cd57-b0ee-4833-bcd1-ff0343dd01cc/?limit=100&ordering=-datetime_uploaded
})
})
});
map.addLayer(markers);
function success(pos) {
const crd = pos.coords;
console.log('Your current position is:');
console.log(`Latitude : ${crd.latitude}`);
console.log(`Longitude: ${crd.longitude}`);
console.log(`More or less ${crd.accuracy} meters.`);
return new Array(crd.latitude, crd.longitude);
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);
var marker = new ol.Feature(new ol.geom.Point(ol.proj.fromLonLat([position.coords.latitude, position.coords.longitude])));
markers.getSource().addFeature(marker);
});
}
else {
alert("Your browser does not support geolocation");
}
});
</script>
I tried to save the coordinates in A list and in a string, but none worked.
here is the Model code:
public class ReportModel
{
//...stuff...
public string coordinates { get; set; }
//...more stuff...
}
ReportDAO.cs - Saves the given data form the user
using Microsoft.Data.SqlClient;
using SvivaTeamVersion3.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SvivaTeamVersion3.Services
{
public class ReportDAO
{
static readonly string connectionString = #"KEY";
public static bool addReport(ReportModel report)
{
bool success = false;
string sqlStatement = "INSERT INTO dbo.Reports (category,title,description,statUrgence,cordsLat,cordsLong) VALUES (#category,#title,#description,#statUrgence,#cordsLat,#cordsLong)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(sqlStatement, connection);
command.Parameters.Add("#category", System.Data.SqlDbType.NChar, 32).Value = report.category;
command.Parameters.Add("#title", System.Data.SqlDbType.NChar, 32).Value = report.title;
command.Parameters.Add("#description", System.Data.SqlDbType.NVarChar, -1).Value = report.remarks;
command.Parameters.Add("#statUrgence", System.Data.SqlDbType.NVarChar, -1).Value = report.statUrgence;
command.Parameters.Add("#cordsLat", System.Data.SqlDbType.Float).Value = report.coordinates;
command.Parameters.Add("#cordsLong", System.Data.SqlDbType.Float).Value = 0;
//I've tried to merge the lat and long to a single string, didn't work.
try
{
connection.Open();
command.ExecuteNonQuery();
success = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return success;
}
}
}
}

Related

Upload File And Reload Same Partial View

Good Evening,
I'm trying to upload a file and when the form submits I just want to reload the partial view in the modal div, not the entire page. I looked at a number of other posts and they suggested to use AJAX but even when I used AJAX, instead of just reloading the partial view popup, It takes me to a full page view of the Partial View. I want to just reload the content inside of the modal div.
Here is my code:
Controller
public PartialViewResult FileUpload(int jobID)
{
ViewBag.jobID = jobID;
return PartialView(GetFiles(jobID));
}
[HttpPost]
public ActionResult FileUpload(int jobID, HttpPostedFileBase files)
{
int id = Convert.ToInt32(Session["id"]);
String FileExt = Path.GetExtension(files.FileName).ToUpper();
if(FileExt == ".PDF")
{
Stream str = files.InputStream;
BinaryReader Br = new BinaryReader(str);
Byte[] FileDet = Br.ReadBytes((Int32)str.Length);
UploadFileModel Fd = new UploadFileModel();
Fd.FileName = files.FileName;
Fd.FileContent = FileDet;
Fd.personID = id;
Fd.jobID = jobID;
file fileDB = new file();
fileDB.FileContent = Fd.FileContent;
fileDB.FileName = Fd.FileName;
fileDB.personID = id;
fileDB.jobID = Fd.jobID;
db.files.Add(fileDB);
db.SaveChanges();
return PartialView("FileUpload", GetFiles(jobID));
}
else
{
ViewBag.FileStatus = "Invalid file format.";
return PartialView();
}
}
[HttpPost]
public FileResult DownloadFile(int? fileId)
{
byte[] bytes;
string fileName, contentType;
var file = db.files.Find(fileId);
bytes = (byte[])file.FileContent;
fileName = file.FileName;
return File(bytes, fileName);
}
public List<UploadFileModel> GetFiles(int jobID)
{
List<UploadFileModel> files = new List<UploadFileModel>();
var filesDB = db.files.Where(x => x.jobID == jobID);
foreach (var fileDB in filesDB)
{
files.Add(new UploadFileModel
{
id = fileDB.id,
FileName = fileDB.FileName,
personID = fileDB.personID,
jobID = fileDB.jobID
});
}
return files;
}
Partial View:
#model IEnumerable<Church_Musician_Administration_App__Updated_.Models.UploadFileModel>
<style>
.table-striped tbody tr:nth-of-type(odd) {
background-color: rgb(222, 178, 241);
}
.table-striped tbody tr:nth-of-type(even) {
background-color: rgb(233, 204, 246);
}
#fileTable {
font-family: "Arial";
}
#fileTable tr {
cursor: default;
}
a:link {
color: darkviolet;
background-color: transparent;
text-decoration: none;
}
a:visited {
color: gray;
background-color: transparent;
text-decoration: none;
}
a:hover {
color: white;
background-color: transparent;
text-decoration: none;
}
a:active {
color: rebeccapurple;
background-color: transparent;
text-decoration: none;
}
</style>
#using (Html.BeginForm("FileUpload", "App", FormMethod.Post, new { enctype = "multipart/form-data", id="fileUploadForm"}))
{
<input type="hidden" name="jobID" value="#ViewBag.jobID" />
<label class="btn btn-primary" for="my-file-selector">
<input id="my-file-selector" name="files" type="file" style="display:none"
onchange="$('#upload-file-info').text(this.files[0].name)">
Choose File
</label>
<span class='label label-info' id="upload-file-info">No File Uploaded</span>
<input class="btn btn-primary" type="submit" id="btnUpload" value="Upload" style="margin-bottom:5px" />
}
#using (Html.BeginForm("DownloadFile", "App", FormMethod.Post))
{
<input type="hidden" id="hfFileId" name="FileId" />
<input type="submit" id="btnDownload" value="Download" style="display:none" />
}
<hr />
<table id="fileTable" class="table table-striped" style="width:100%; border: 1px solid rgba(0,0,0,.125); border-left:none; border-right:none; text-align: center; display:inline-table;">
<tbody>
<tr style="background-color:darkviolet; height:40px; width:100%">
<th style="display:none;">JobID</th>
<th style="display:none">File ID</th>
<th style="color:white; border: 1px solid rgba(0,0,0,.125);">File Name</th>
<th style="color:white; border: 1px solid rgba(0,0,0,.125);">Download</th>
</tr>
#if (Model.Count() > 0)
{
foreach (var file in Model)
{
<tr>
<td style="display:none;">#file.id</td>
<td style="border: 1px solid rgba(0,0,0,.125);">#file.FileName</td>
<td style="border: 1px solid rgba(0,0,0,.125);">Download</td>
</tr>
}
}
else
{
<tr>
<td colspan="3"> </td>
</tr>
}
</tbody>
</table>
<script type="text/javascript">
function DownloadFile(fileId) {
$("#hfFileId").val(fileId);
$("#btnDownload")[0].click();
};
</script>
<script>
$('#btnUpload').click(function (event) {
event.preventDefault();
event.stopImmediatePropagation();
$('#fileUploadForm').submit();
$.ajax({
url: '/App/FileUpload',
type: 'POST',
success: function (data) {
$("#addMusicModalBodyDiv").html(data);
$("#addMusicModal").modal("show");
}
});
});
</script>
EDIT: Here is the code for where the addMusicModal is defined. It's located in a view called ViewSubstituteJobs
<button type="button" class="btn btn-primary" id="addMusic" onclick="addMusic()">Add Music</button>
<div class="modal" tabindex="-1" id="addMusicModal">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add Music</h5>
<button type="button" class="close" aria-label="Close" id="closeAddMusicModal" onclick="closeDialog()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="addMusicModalBodyDiv">
</div>
</div>
</div>
</div>
var addMusic = function () {
var idFromTable = $("#subJobs tr").closest('tr.highlight').find('td:eq(0)').text();
if (idFromTable == 0) {
return false;
}
$.ajax({
type: "GET",
url: "/App/FileUpload",
data: {
jobID: idFromTable,
},
success: function (response) {
$(".modal").modal("hide");
$("#addMusicModalBodyDiv").html(response);
$("#addMusicModal").modal("show");
}
})
}
</script>

MVC-5 WebGrid adding Column headers as actionlinks

I am dynamically adding columns to a Web-grid using MVC-5 and C# and when the grid renders everything looks fine but the column headers won't function as an action Links. There are two versions of the code and both render but don't function as Action Links.
Thank you for your help.
cols.Add(grid.Column(Model.DictionaryList[i].Keys.ElementAt(i).ToString(), Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
format: #<Text>#Html.ActionLink((string)Model.DictionaryList[i].Values.ElementAt(i).ToString(), "Select_MSPart_Search",
"MaterialSupply", new
{
id = ViewData["id"],
type = 1,
SearchFilter = Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
SearchValue = "",
rowsPerPage = 7
})</Text>, style: "column-action"));
cols.Add(grid.Column(header: Model.DictionaryList[i].Keys.ElementAt(i).ToString(),columnName: Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
format: (item) => new HtmlString(Html.ActionLink((string)Model.DictionaryList[i].Values.ElementAt(i).ToString(), "Select_MSPart_Search",
"MaterialSupply", new
{
id = ViewData["id"],
type = 1,
SearchFilter = Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
SearchValue = "",
rowsPerPage = 7
},null).ToHtmlString()), style: "column-action"));
Everything seems to render correctly except the column headers are not Action Links as I had hoped for. I also tried the second piece of code with the same results.
Thank you for your help.
I realized that seeing the entire view would be critical because I am building the grid dynamically.
#using System.Dynamic
#using System.Linq
#using System.Data.Common
#using CeleroPortal.Models.ConstraintsAnalysis
#using System.Collections.Generic
#using System.Web.Mvc.Html
#using System.Web.Mvc.Razor
#model mdlViews
#using PagedList.Mvc
#{
ViewBag.Title = "View Report records Page";
var result = new List<dynamic>();
int rowcnt = 0;
foreach (var recRow in Model.DlList)
{
var row = (IDictionary<string, object>)new ExpandoObject();
Dictionary<string, object> eachFieldRow = (Dictionary<string, object>)recRow; //for when list was string,object
foreach (KeyValuePair<string, object> keyValuePair in eachFieldRow)
{
row.Add(keyValuePair.Key, keyValuePair.Value);
}
result.Add(row);
rowcnt++;
}
//WebGrid grid = new WebGrid(source: result, rowsPerPage: Model.PageSize, canPage: true, canSort: true, sortFieldName: Model.Sort, sortDirectionFieldName: Model.SortDir);
WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize, canPage: true, canSort: false, sortFieldName: Model.Sort, sortDirectionFieldName: Model.SortDir);
List<WebGridColumn> cols = new List<WebGridColumn>();
cols.Add(grid.Column("Order ID","Order ID"));
cols.Add(grid.Column("Part ID", "Part ID"));
cols.Add(grid.Column("Description", "Description"));
cols.Add(grid.Column("Customer ID", "Customer ID"));
cols.Add(grid.Column("Customer", "Customer"));
cols.Add(grid.Column("Qty Due", "Quantity Due"));
cols.Add(grid.Column("Target Date", "Target Date"));
cols.Add(grid.Column("Days", "Days"));
cols.Add(grid.Column("Final Date", "Final Date"));
for (int i = 9; i < Model.DictionaryList[0].Count(); i++)
{
if (Model.DictionaryList[0].Keys.ElementAt(i).StartsWith("#"))
{
cols.Add(grid.Column(Model.DictionaryList[0].Keys.ElementAt(i).ToString(), Model.DictionaryList[0].Keys.ElementAt(i).ToString()));
}
else
{
//cols.Add(grid.Column(Model.DictionaryList[i].Keys.ElementAt(i).ToString(),header: Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
// format: (Model) => Html.ActionLink((string)Model.DictionaryList[i].Values.ElementAt(i).ToString(), "Select_MSPart_Search",
// "MasterSupply",new { id = ViewData["id"] , type = 1, SearchFilter = Model.DictionaryList[i].Keys.ElementAt(i).ToString() , SearchValue = "",
// rowsPerPage = 7}),style: "column-action"));
cols.Add(grid.Column(header:Model.DictionaryList[i].Keys.ElementAt(i).ToString(),columnName: Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
format: #<Text>#Html.ActionLink((string)Model.DictionaryList[i].Values.ElementAt(i).ToString(), "Select_MSPart_Search",
"MaterialSupply", new
{
id = ViewData["id"],
type = 1,
SearchFilter = Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
SearchValue = "",
rowsPerPage = 7
})</Text>, style: "column-action"));
//cols.Add(grid.Column(header: Model.DictionaryList[i].Keys.ElementAt(i).ToString(),columnName: Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
// format: (item) => #Html.ActionLink((string)Model.DictionaryList[i].Values.ElementAt(i).ToString(), "Select_MSPart_Search",
// "MaterialSupply", new
// {
// id = ViewData["id"],
// type = 1,
// SearchFilter = Model.DictionaryList[i].Keys.ElementAt(i).ToString(),
// SearchValue = "",
// rowsPerPage = 7
// }, null)));
}
}
grid.Bind(result, rowCount: Model.TotalRecords, autoSortAndPage: true);
grid.Pager(WebGridPagerModes.All);
}
<style type="text/css">
.webgrid-table {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
font-size: 1.2em;
width: 100%;
display: table;
border-collapse: separate;
border: solid 1px #000066; /*#98BF21;*/
background-color: white;
}
.webgrid-table td, th {
border: 1px solid #000099; /*#98BF21;*/
padding: 3px 7px 2px;
}
.webgrid-header {
background-color: #b3d9ff; /*#A7C942;*/
color: #FFFFFF;
padding-bottom: 4px;
padding-top: 5px;
text-align: left;
}
.webgrid-footer {
}
.webgrid-row-style {
padding: 3px 7px 2px;
}
.webgrid-alternating-row {
background-color: #e6f2ff; /*#EAF2D3;*/
padding: 3px 7px 2px;
}
.webgrid-selected-row {
background-color: #ffff66; /*#EAF2D3;*/
padding: 3px 7px 2px;
}
</style>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<div class="jumbotron">
<h1><img src="~/Images/Celero.png" /></h1>
<p class="lead">Constraints Analysis Application Pushed Orders Grid</p>
<div>
#Html.ActionLink("Search for Part across reports", "Select_MSPart", "MaterialSupply", new { id = ViewData["Id"].ToString(), type = ViewData["type"]},null)
</div>
</div>
<div class="row">
#using (Html.BeginForm("Views", "ConstraintsAnalysis", new { id = ViewData["id"], type = ViewData["type"] }, FormMethod.Post))
{
<div class="row">
<div class="form-horizontal" style="float: left">
<div class="col-md-4">
#if (Model.RwsPrPge == Model.TotalRecords)
{
<select id="rwsPrPge" name="rwsPrPge">
<option value="5">50</option>
<option value="0">All</option>
</select>
}
else
{
<select id="rwsPrPge" name="rwsPrPge">
<option value="0">All</option>
<option value="5">50</option>
</select>
}
<input type="submit" value="Rows/Page" />
#Html.Hidden("id", (object)ViewData["Id"].ToString())
#Html.Hidden("type", (object)ViewData["type"].ToString())
</div>
<div class="col-lg-4">
#*#Html.DropDownListFor(Model => Model.SearchFilter, new SelectList(ViewBag.SelectFilter, "Value", "Text"),
"Select Part for Search", new { #class = "form-control", #placeholder = "Search Filter" })*#
#Html.DropDownList("m", new SelectList(ViewBag.SelectFilter, "Value", "Text"), "Select Part")
</div>
<div class="col-lg-4" float="right">
 
<button type="submit" class="btn btn-success" value="m">
<span class="glyphicon glyphicon-search"></span>
</button>
</div>
<br /><br />
<div class="col-md-4">
<select id="Export" name="Export">
<option value="00">No Export</option>
<option value="XX">Export to CSV</option>
#Html.EditorFor(model => model.DlList)
#Html.ValidationMessageFor(model => model.DlList)
</select>
</div>
<div class="col-md-4">
<button type="submit" class="btn btn-success" value="Export" href="/ConstraintsAnalysis/Views">
<span class="glyphicon glyphicon-export"></span>
</button>
</div>
</div>
</div>
if (Model != null)
{
<span>
<span class="vam" style="float: left">
#Html.ActionLink("Report Selection Menu", "Index", "ConstraintsAnalysis")
</span>
<span class="vam">
#grid.GetHtml(tableStyle: "table table-bordered table-hover",
headerStyle: "webgrid-header",
footerStyle: "webgrid-footer",
alternatingRowStyle: "webgrid-alternating-row",
selectedRowStyle: "webgrid-selected-row",
caption: "Celero Constraints Grid",
rowStyle: "webgrid-row-style");
</span>
</span>
}
}
</div>
I found the problem. I forgot the columns: cols on the #grid.GetHtml.
Thank you

Display More then 10000 records in JqGrid

IN my Database table i have more then 30,000 records,here i am trying to Display these records in JqGrid,Here i displayed upto 900 records only, How can i display all records in JqGrid,here i am attaching my code.
<script type="text/javascript">
$(function () {
$("#dataGrid").jqGrid({
url: 'Default.aspx/GetDataFromDB',
datatype: 'json',
mtype: 'POST',
overflow:'visible',
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
ajaxGridOptions: { contentType: "application/json" },
loadonce: true,
colNames: ['AOfficeKey', 'AChartNumber', 'APatientName', 'AVisit#'],
colModel: [
{ name: 'AOfficeKey', index: 'AOfficeKey', width: 80 },
{ name: 'AChartNumber', index: 'AChartNumber', width: 150 },
{ name: 'APatientName', index: 'APatientName', width: 160 },
{ name: 'AVisit#', index: 'AVisit#', width: 160 }
],
pager: '#pagingGrid',
rowNum: 100,
height: 300,
width:600,
rowList: [10, 100, 1000, 10000],
gridview: true,
viewrecords: true,
gridview: true,
jsonReader: {
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.d.length; },
root: function (obj) { return obj.d; },
repeatitems: false,
id: "0"
},
});
});
</script>
</head>
<body style="font-family: Arial; font-size: 10pt">
<table style="border: solid 1px ; width: 100%; vertical-align: central;">
<tr>
<td style="padding-left: 20px; padding-top: 20px; padding-bottom: 20px; font-family: 'Times New Roman'; font-weight: bold; font-size: 20pt; color: chocolate;">
</td>
</tr>
<tr>
<td style="text-align: center; vertical-align: central; padding: 100px;">
<table id="dataGrid" style="text-align: center; width: 100%;"></table>
<div id="pagingGrid"></div>
</td>
</tr>
</table>
C# code is
[WebMethod]
public static List<Dictionary<string, object>> GetDataFromDB()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(#"Data Source=Abc;Database=Training;User Id=sa;Password=abc;"))
{
using (SqlCommand cmd = new SqlCommand("SELECT * AOfficeKey,AChartNumber, APatientName,AVisit# from adjs", con))
//("SELECT ID,Client,Location,Address FROM AClients ", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return rows;
}
}
}
I've tried your code and it works without error. However in order to load large data from server you will need to increase allowed JSON size when using json serialization. In order to do it past following code to your web.config in the <configuration> tag:
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>

ExtJS. Get images from database

My image viewer :
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="http://cdn.sencha.com/ext/gpl/5.1.0/build/packages/ext-theme-classic/build/resources/ext-theme-classic-all.css">
<script type="text/javascript" src="http://cdn.sencha.com/ext/gpl/5.1.0/build/ext-all.js"></script>
<script type="text/javascript" src="http://cdn.sencha.com/ext/gpl/5.1.0/build/packages/ext-theme-classic/build/ext-theme-classic.js"></script>
<style>
.thumbnail {
padding: 4px;
background-color: #e6e6e0;
border: 1px solid #d6d6d0;
float: left;
margin-right: 10px;
margin-bottom: 10px;
cursor: pointer;
}
</style>
</head>
<body>
<script>
Ext.define('Image', {
extend: 'Ext.data.Model',
fields: [
{ name: 'href', type: 'string' },
{ name: 'caption', type: 'string' }
]
});
var imagesStore = Ext.create('Ext.data.Store', {
id: 'imagesStore',
model: 'Image',
data: [
{ href: 'images/Hydrangeas.jpg', caption: 'Hydrangeas' },
{ href: 'images/Jellyfish.jpg', caption: 'Jellyfish' },
{ href: 'images/Koala.jpg', caption: 'Koala' },
{ href: 'images/Lighthouse.jpg', caption: 'Lighthouse' }
]
});
var imageTpl = new Ext.XTemplate(
'<tpl for=".">',
'<div class="thumbnail" onClick="javascript:openWindow(this.lightbox);" >',
'<img src="{href}" width="200px" height="150px" />',
'<br/><span>{caption}</span>',
'</div>',
'</tpl>'
);
var sel_thumb_id = 0;
var thumbs = Ext.create('Ext.view.View', {
id: 'thumbs',
store: Ext.data.StoreManager.lookup('imagesStore'),
tpl: imageTpl,
itemSelector: 'img',
emptyText: 'No images available',
renderTo: document.body,
listeners: {
}
});
var img = Ext.create('Ext.Img', {
id:'img',
src: '',
shrinkWrap: true
});
var next = Ext.create('Ext.Button', {
xtype: 'button',
text: 'Next',
width: 100,
handler: function () {
if (img_id < imagesStore.data.items.length ) {
img_id = img_id + 1;
var nextSrc = imagesStore.data.items[img_id].data.href;
console.log(nextSrc);
Ext.getCmp('img').setSrc(nextSrc);
}
}
});
var previous = Ext.create('Ext.Button', {
xtype: 'button',
text: 'Previous',
width: 100,
handler: function () {
if (img_id > 0) {
img_id = img_id - 1;
var nextSrc = imagesStore.data.items[img_id].data.href;
Ext.getCmp('img').setSrc(nextSrc);
}
}
});
var lightbox = new Ext.window.Window( {
id: 'lightbox',
title: '',
height: 600,
width: 800,
layout: 'fit',
items: [img],
modal: true,
draggable: false,
dockedItems: [{
xtype: 'toolbar',
dock: 'bottom',
padding: '5 20',
align: 'center',
items: [previous, next]
}],
closeAction: 'hide',
resizable: false
})
function openWindow(lightbox) {
img.setSrc('images/Hydrangeas.jpg');
Ext.getCmp('lightbox').show();
img_id = 0;
}
</script>
</body>
In this way, images are stored in a folder. Now i want to load images from database. I don't mean image path from database, i mean image. I can get images data from database using c# asmx web service.
1) What type should i choose to store images in ms sql ?
2) How can i convert data that i will get from database and display as images ?

C# array to MVC view for Google Map markers

I am having such a rough time accomplishing this and all the research I'm doing is not turning out positive. In short, I need to send an array of markers from my code to my MVC view (through the model and setting it as a hidden field) so that the Google map can use this array to place markers on the map. I have tried building it as a List and then using JSON serialization to turn it to a string, but the format just won't turn out and won't be recognizable to the Google API. Has anyone done this before successfully??
Here is my updated code based on CodeMonkey's answer, but the markers still aren't placing. I think it's happening somewhere in the addMarker function...
var lat = $("#Latitude").val();
var lng = $("#Longitude").val();
var myOptions = {};
var map = null;
var marker = null;
var global_markers = [];
var infowindow = new google.maps.InfoWindow({});
var geodata;
var markers = [];
function map_initialize() {
var myLatlng = new google.maps.LatLng(lat, lng);
myOptions = {
zoom: 14,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
#foreach (var item in Model.AllSearchResults)
{
<text>try
{
var lat = '#item.Latitude';
var lng = '#item.Longitude';
var name = '#item.Name';
var url = '#Url.Action("GetMarker", "Base")';
var model = { "Latitude": lat, "Longitude": lng, "Name": name };
$.ajax({
type: "POST",
data: model,
dataType: "json",
url: url,
success: function (data) {
geodata = data;
JSONString = JSON.stringify(geodata);
var valuesToPush = new Array();
valuesToPush[0] = data.Latitude;
valuesToPush[1] = data.Longitude;
valuesToPush[2] = data.Name;
markers.push(valuesToPush);
addMarker();
},
error: function () {
alert("fail");
}
});
}
catch (err) { }</text>
}
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var name = markers[i][2];
var location = new google.maps.LatLng(lat, lng);
var contentString = '<div class="infowindow"><p>' + name + '</p></div>';
var marker = new google.maps.Marker({
position: location,
map: map,
title: name
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function () {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
google.maps.event.addDomListener(window, 'load', map_initialize);
I was able to do a combo server side/client side approach using the following link as a guide: http://mikehadlow.blogspot.com/2008/10/using-google-maps-with-mvc-framework.html
Thanks for Code Monkey's input!!
You can reference my front-end JS code at this URL: http://www.wallodex.com/WallodexAdmin/Map/10
This is how I use it on the VIEW:
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>CloudClaims Administration - Site Visits</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDgJDbn0VP_AnX4HsXSjN3cIn0MoEJ4vOw&sensor=false"></script>
<script type="text/javascript" src="../../js/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="../../js/json2.js"></script>
<script type='text/javascript'>
var DISPLAY_COUNT = 20;
var myOptions = {};
var markerArray = new Array();
var map = null;
//var geocoder = null;
var marker = null;
var g_ctr = 0;
var last_used_address = "";
var splitURLs = {};
var global_markers = [];
var infowindow = new google.maps.InfoWindow({});
var geodata;
var markers = [];
function initialize() {
myOptions = {
center: new google.maps.LatLng(38.5111, -96.8005),
zoom: 4,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//geocoder = new google.maps.Geocoder();
#foreach (var item in Model)
{
<text>try
{
var ip = '#item';
var url = 'http://api.ipinfodb.com/v3/ip-city/?format=json&key=6d0759103a4ec817ffda18dfba4eafe853125d6960dedffdcfa4a428774d871d&ip=' + ip + '&callback=?';
$.getJSON(url,
function (data) {
if (data['statusCode'] == 'OK') {
geodata = data;
JSONString = JSON.stringify(geodata);
//callback();
//alert(data.regionName);
var valuesToPush = new Array();
valuesToPush[0] = data.latitude;
valuesToPush[1] = data.longitude;
valuesToPush[2] = data.cityName + ', ' + data.regionName;
valuesToPush[3] = data.ipAddress;
markers.push(valuesToPush);
addMarker();
}
});
}
catch (err) { }</text>
}
}
function addMarker() {
for (var i = 0; i < markers.length; i++) {
var lat = parseFloat(markers[i][0]);
var lng = parseFloat(markers[i][1]);
var cityState = markers[i][2];
var ipAddress = markers[i][3];
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = '<div class="infowindow"><p>' + cityState + '<br/>' + ipAddress + '</p></div>';
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " \n Location: " + cityState
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function () {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".fadeInbox").hide().fadeIn(4000);
$("#map_canvas").hide().fadeIn(4000);
$(".subscriberList").hide().fadeIn(8000);
});
$(window).load(function () {
$("#loading").css('visibility', 'hidden');
});
</script>
<style type="text/css">
.infowindow
{
background-color: Yellow;
text-align: left;
padding: 0px, 0px, 0px, 0px;
margin: 0px, 0px, 0px, 0px;
}
.fadeOutbox, .fadeInbox, .fadeTobox
{
padding: 10px;
margin: 4px;
border: 1px solid blue;
width: 250px;
height: 50px;
background-color: #000000;
color: white;
font: georgia;
}
.clear
{
clear: both;
}
</style>
</head>
<body onload="initialize();">
<form id="form1" runat="server">
<asp:panel id="Panel1" runat="server" style="height: 600px;">
<asp:Literal ID="js" runat="server"></asp:Literal>
<table width="100%" align="center" border="1">
<tr bgcolor="#1569C7" align="center">
<td colspan="2">
<font color="white">CloudClaims™ - Site visitors - Last X days</font>
</td>
</tr>
<tr align="center">
<td width="80%">
<div id="map_canvas" style="width: 100%; height: 620px; margin-bottom: 0.5px;"></div>
</td>
<td align="center" valign="bottom" bgcolor="#FFBD82">
<asp:Label runat="server" id="errors"/>
<div>
#{Html.RenderAction("Subscribers");}
</div>
<div align="center" class="fadeInbox">
<b>DEBUGGING</b><br />
<asp:Label runat="server" id="ajaxtest"/>
</div>
</td>
</tr>
</table>
</asp:panel>
</form>
</body>
</html>
And this is my CONTROLLER (I convert IP ADDRESSES to gMap objects on the front-end but you get the idea...):
public ActionResult Map(int id)
{
try
{
using (var db = new CloudClaimsEntities())
{
DateTime dateFrom = (id != null && id > 1) ? DateTime.Now.AddDays(-id) : DateTime.Now.AddDays(-1);
List<string> IPAddresses = new List<string>();
IPAddresses = db.IPLogs
.Where(i => i.timeStamp <= DateTime.Now)
.Where(i => i.timeStamp >= dateFrom)
.Select(i => i.IPAddress)
.ToList();
return View(IPAddresses);
}
}
catch
{
return View();
}
}

Categories