HTML select element firing an onclick event in C# - c#

In my Visual Studio project (ASP.NET Web Forms), I have a <select> in the HTML file:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="clientes.aspx.cs" Inherits="Leo.clientes" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
margin: 0;
font-family: Arial, Helvetica, sans-serif;
}
.topnav {
overflow: hidden;
background-color: #333;
}
.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #4CAF50;
color: white;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="topnav">
Dashboard
<a class="active" href="/clientes">Clientes</a>
Despesas
</div>
<div style="padding-left:16px">
<label for="cars">Cliente:</label>
<select name="listaClientes" id="listaClientes" onserverchange="escolherCliente" runat="server">
</select>
</div>
</form>
</body>
</html>
In my cs file, I have a function called escolherCliente. This function is called by using the onserverchange event above.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using MySql.Data.MySqlClient;
namespace Leo
{
public partial class clientes : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string mycon = "server = localhost; Uid = Leo; password = password; persistsecurityinfo = True; database = db; SslMode = none";
MySqlConnection con = new MySqlConnection(mycon);
MySqlCommand cmd = null;
try
{
cmd = new MySqlCommand("select nome from cliente;", con);
con.Open();
MySqlDataReader leitor = cmd.ExecuteReader();
while(leitor.Read())
{
listaClientes.Items.Add(new ListItem(leitor.GetString(0)));
}
con.Close();
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
con.Close();
}
}
protected void escolherCliente(object sender, EventArgs e)
{
Response.Write("<script>alert('fdasfdsfsdfasfsafds')</script>");
}
}
}
The problem is that the function is not getting called. I change the selected <option> in the <select>, and nothing happens.
I already tried using onchange instead of onserverchange, and it also didn't work.
What should I do?

Related

How to save coordinates from with openlayers ASP.NET

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;
}
}
}
}

iTextSharp CSS not getting applied properly

I am trying to use iTextSharp to convert HTML to PDF but CSS properties like border-radius is not working. This is my code:
using (MemoryStream stream = new System.IO.MemoryStream())
{
string goldenHourTemplate = System.IO.File.ReadAllText(Path.Combine(_environment.ContentRootPath, #"Templates\GoldenHour-Main-Template.html"));
string goldenHourStepTemplate = System.IO.File.ReadAllText(Path.Combine(_environment.ContentRootPath, #"Templates\GoldenHour-Step-Template.html"));
string goldenHourCss = System.IO.File.ReadAllText(Path.Combine(_environment.ContentRootPath, #"Templates\golden-hour.css"));
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(goldenHourCss)))
{
using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(goldenHourTemplate)))
{
pdfDoc.Open();
//Parse the HTML
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, msHtml, msCss);
pdfDoc.Close();
System.IO.File.WriteAllBytes(#"C:\Test\Test.pdf", stream.ToArray());
}
}
}
This is my CSS file:
body {
font-family: Arial, sans-serif;
}
ul {
list-style: none;
margin: 0px;
padding: 0px;
}
.step-item {
padding: 15px 20px;
border: solid 1px #c1c1c1;
border-radius: 5px;
margin-bottom: 10px;
display: inline-block;
width: 250px;
text-align: center;
background: #d9d9dc;
vertical-align: top;
}
.green-circle {
background: #92d050;
width: 50px;
height: 50px;
border-radius: 50px;
display: inline-block;
margin-left: 50px;
}
.red-circle {
background: #ff0000;
width: 50px;
height: 50px;
border-radius: 50px;
display: inline-block;
margin-left: 50px;
}
.grey-circle {
background: #7f7f7f;
width: 50px;
height: 50px;
border-radius: 50px;
display: inline-block;
margin-left: 50px;
}
This is my template.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
#:{Steps}:#
<ul>
<li>
<div class="step-item">Correct Rack Allocation</div> <div class="green-circle"></div>
</li>
<li>
<div class="step-item">Fibres Present</div> <div class="red-circle"></div>
</li>
<li>
<div class="step-item">Power & Earth Present</div> <div class="green-circle"></div>
</li>
<li>
<div class="step-item">DCN Connectivity</div> <div class="grey-circle"></div>
</li>
<li>
<div class="step-item">Rack Space</div> <div class="green-circle"></div>
</li>
</ul>
</body>
</html>
but the resulting PDF generated has all messed up format like this:
whereas in reality the HTML is like this:
Please let me know what am I missing?

delayed rediraction asp.net

so I have a login page and I'm trying to have it say "the user doesn't exist" and have it redirect you to the signup page immediately after showing this message, but my current code simply redirects you without displaying the message.
sorry if the message is unclear, its the first time i ever write anything in here:)
ulogin.html page:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="ulogin.aspx.cs" Inherits="User_ulogin" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style5 {
position: absolute;
top: 62px;
left: 53px;
z-index: 1;
}
.auto-style6 {
position: absolute;
top: 140px;
left: 56px;
z-index: 1;
}
.auto-style7 {
position: absolute;
top: 67px;
left: 279px;
z-index: 1;
width: 289px;
}
.auto-style8 {
position: absolute;
top: 141px;
left: 304px;
z-index: 1;
width: 295px;
}
.auto-style9 {
position: absolute;
top: 207px;
left: 219px;
z-index: 1;
}
.auto-style11 {
position: absolute;
top: 277px;
left: 10px;
z-index: 1;
width: 256px;
}
.auto-style12 {
position: absolute;
top: 16px;
left: 244px;
z-index: 1;
}
</style>
</head>
<body style="z-index: 1; width: 1490px; height: 16px; position: absolute; top: 0px; left: 0px">
<form id="form1" runat="server">
<div style="width: 1400px; margin: 0 auto;">
<asp:Label ID="Label2" runat="server" CssClass="auto-style5" Text="username:" Font-Size="18pt" Font-Bold="True"></asp:Label>
<asp:Label ID="Label3" runat="server" CssClass="auto-style6" Text="password:" Font-Size="18pt" Font-Bold="True"></asp:Label>
<asp:TextBox ID="txtuser" runat="server" CssClass="auto-style7" BorderColor="Black" OnTextChanged="txtuser_TextChanged"></asp:TextBox>
<asp:TextBox ID="txtpass" runat="server" CssClass="auto-style8" BorderColor="Black" OnTextChanged="txtpass_TextChanged"></asp:TextBox>
<asp:Button ID="Button1" runat="server" CssClass="auto-style9" OnClick="Button1_Click" Text="connect now" BackColor="Azure" Font-Size="16pt" BorderColor="Black" />
<asp:HyperLink ID="HyperLink1" runat="server" CssClass="auto-style11" Font-Size="14pt" Font-Underline="True">lost your password? reset it now</asp:HyperLink>
**<asp:Label ID="lblsucc" runat="server" style="z-index: 1; left: 746px; top: 97px; position: absolute" Text="user dont exist" Visible="False"></asp:Label>**
<asp:Label ID="Label4" runat="server" CssClass="auto-style12" Font-Size="XX-Large" Text="Sign Now"></asp:Label>
</div>
</form>
</body>
</html>
ulogin.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class User_ulogin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lblsucc.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
users user = new users();
admin adn = new admin(txtuser.Text, txtpass.Text);
user.User_Name = txtuser.Text;
user.Pass = txtpass.Text;
if (user.login(user))
{
Session["user"] = txtuser.Text;
Response.Redirect("homepage.aspx");
}
else
{
lblsucc.Visible = true;
}
if(user.ifexist(user))
Response.Redirect("uregister.aspx");
}
protected void txtuser_TextChanged(object sender, EventArgs e)
{
}
protected void txtpass_TextChanged(object sender, EventArgs e)
{
}
protected void ImageButton2_Click1(object sender, ImageClickEventArgs e)
{
Response.Redirect("homepage.aspx");
}
}
'''
the relevant classes codes:
''' public bool login(users us)
{
DataSet dsUser = new DataSet();
string stuser = "SELECT tblUsers.User_Name, tblUsers.User_Password FROM tblUsers WHERE(((tblUsers.User_Password) = '" + us.user_Name + "')AND((tblUsers.User_Password) = '" + us.Pass + "')); ";
dsUser = sql.chkData(stuser);
if (dsUser.Tables[0].Rows.Count > 0)
{
return true;
}
else return false;
}'''
'''public bool ifexist(users user)
{
bool chk = false;
DataSet dsUser = new DataSet();
string stuser = "SELECT tblUsers.User_Name FROM tblUsers WHERE(((tblUsers.User_Name) ='" + user.User_Name + "'));";
dsUser = sql.chkData(stuser);
if (dsUser.Tables[0].Rows.Count > 0)
chk = true;
return chk;
}'''

RazorEngineService.RunCompile(): The name 'section' does not exist in the current context

I have this sub layout trying to define a section via #section to render in a main layout named _MainLayout.cshtml
_SubLayout.cshtml
#{ Layout = "_MainLayout"; }
#section Styles {
<style>
.container { width: 50%; }
</style>
}
<div class="container"></div>
then here is where it is expected to be rendered via #RenderSection("Styles", false)
_MainLayout.cshtml
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html charset=UTF-8" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700">
<style>
html,
body {
margin: 0 !important;
padding: 0 !important;
height: 100% !important;
width: 100% !important;
}
#RenderSection("Styles", false)
</style>
</head>
<html>
<body>
#RenderBody()
</body>
</html>
but I am getting this while compiling the razor templates via RazorEngineService.RunCompile()
private string RenderTemplate<T>(string view, List<string> layouts, T model)
{
string template = GetTemplate(view);
var config = new TemplateServiceConfiguration();
using (var service = RazorEngineService.Create(config))
{
if (layouts != null)
foreach (var layout in layouts)
{
var templateLayout = GetTemplate(layout, "Shared");
if (!string.IsNullOrEmpty(templateLayout))
service.AddTemplate(layout, templateLayout);
}
return service.RunCompile(template, new Guid().ToString(), typeof(T), model);
};
}
private string GetTemplate(string view, string subFolderName = "")
{
var root = Directory.GetCurrentDirectory();
var location = Path.Combine(root, "Views", "Email");
if(!string.IsNullOrEmpty(subFolderName))
location = Path.Combine(location, subFolderName);
var file = Path.Combine(location, view + ".cshtml");
if (!File.Exists(file))
return "";
return File.ReadAllText(file);
}

pdf objects won't display in IE but will in Chrome

I am at my wits end.
The following code displays a pdf to the user based on a query string and pulls the pdf from a file server. It works great in google chrome. However, I need this to work in IE as well.
When I use IE, it just shows a blank space where the pdf should be. Below is my aspx and C# file. Both browsers have adobe reader addons installed.
FRONT END:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JobBookViewer.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Job Book Viewer</title>
<style type="text/css">
#form1 {
font-weight: 700;
width: 118px;
height: 217px;
margin-top: 15px;
}
</style>
<script type="text/javascript">
function SetPDFwindow()
{
var varclientscreenwidth = screen.width;
var varclientscreenheight = screen.height;
}
</script>
</head>
<body onload="SetPDFwindow()">
<form id="form1" runat="server">
<div style="width: 203px; z-index: 1; left: 7px; top: 4px; position: relative; height: 34px; right: 811px;">
<asp:Button ID="ButtonAbout" runat="server" BackColor="#B0F1FF" style="z-index: 1; left: 873px; top: 1px; position: absolute" Text="About" OnClick="ButtonAbout_Click" Visible="false" />
<asp:ListBox ID="ListBox1" runat="server" style="z-index: 1; left: 735px; top: 41px; position: absolute; width: 206px; height: 447px;" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged" AutoPostBack =" true"></asp:ListBox>
</div>
<div id="chromecheck" runat="server" visible="false">
Chrome
</div>
<div id="iecheck" runat="server" visible="false">
We have detected that you are not using Chrome. If the program is not working, please switch to Chrome
</div>
<object data="data:application/pdf;base64
, <%= this.file %>" type="application/pdf"
style="z-index: 1; left: -3px; top: 1px; height: 210%; width: 612%; margin-top: 1px;" id="myPDF"></object>
<p>
</p>
</form>
</body>
</html>
CODE BEHIND:
using System;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing;
namespace JobBookViewer
{
public partial class WebForm1 : System.Web.UI.Page
{
public String file;
public String id;
protected void Page_Load(object sender, EventArgs e)
{
System.Web.HttpBrowserCapabilities browser;
browser = Request.Browser;
if (browser.Browser.ToLower().Equals("chrome"))
{
chromecheck.Visible = true;
}
else
{
iecheck.Visible = true;
}
if (!IsPostBack)
{
// myPDF.Style.Add("width", (Convert.ToInt32(clientScreenWidth.Value)-200).ToString());
file = fnFilePDFName(#"\\spfs1\stone\Long Term Share\db_objects\JobBookViewer\select_mold.pdf");
try
{
if (!String.IsNullOrEmpty(Page.Request.QueryString["MoldID"])) // if the string is not null
{
id = (Page.Request.QueryString["MoldID"]);
ListBox1.Items.Clear();
System.IO.DirectoryInfo dinfo = new System.IO.DirectoryInfo(#"\\spfs1\stone\mold_books\" + id.ToString());
System.IO.FileInfo[] Files = dinfo.GetFiles("*.pdf");
foreach (System.IO.FileInfo file in Files)
{
ListBox1.Items.Add(file.Name);
}
}
}
catch { }
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
file = fnFilePDFName(#"\\spfs1\stone\mold_books\" + Page.Request.QueryString["MoldID"] + #"\" + ListBox1.SelectedValue);
}
private string ModifyQueryStringValue(string p_Name, string p_NewValue)
{
var nameValues = System.Web.HttpUtility.ParseQueryString(Request.QueryString.ToString());
nameValues.Set(p_Name, p_NewValue);
string url = Request.Url.AbsolutePath;
string updatedQueryString = "?" + nameValues.ToString();
return url + updatedQueryString;
}
public string fnFilePDFName(string path)
{
string sfileContent;
Byte[] bytes = File.ReadAllBytes(path);
sfileContent = Convert.ToBase64String(bytes);
return sfileContent;
}
}
}

Categories