ASP.NET Button onklick resets label text - html

I am developing my first web application. I am trying to get the GPS location and save it for further processing. This is the code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="CreatePlace.aspx.cs" Inherits="BeeMaster.CreatePlace" %>
<!DOCTYPE html>
<html style="background-image:url('images/background.png'); background-repeat:repeat-x">
<head runat="server">
<title>Create new Place</title>
<link href="CreatePlace.css" rel="stylesheet" type="text/css" />
<style type="text/css">
#taComment {
height: 142px;
width: 339px;
}
</style>
</head>
<body>
<img src="Images/CNP.png" id="logo"/>
<br />
<br />
<br />
<br />
<br />
<br />
<div>
<p id="Comment" style="font-size: large">Click the button to get your position.</p>
<button onclick="getLocation()" style="font-size: xx-large; width: 380px; height: 50px;">
Get current location
</button>
<br />
<asp:Label ID="lblCoordinates" runat="server"></asp:Label><asp:Label ID="lblLat" runat="server"></asp:Label>,<asp:Label ID="lblLon" runat="server"></asp:Label>
<br />
<iframe
height="600"
style="border:0"
id="iFrame">
</iframe>
</div>
<form runat="server">
<br style="font-size: x-large" />
<br style="font-size: x-large" />
<asp:Label ID="lblName" runat="server" Text="Name:" Font-Size="X-Large"></asp:Label>
<br style="font-size: x-large" />
<asp:TextBox ID="tbName" runat="server" Font-Size="X-Large"></asp:TextBox>
<br style="font-size: x-large" />
<asp:Label ID="lblNameComment" runat="server" Text="It is recommended to give a name for the place." Font-Size="Medium"></asp:Label>
<br style="font-size: x-large" />
<br style="font-size: x-large" />
<asp:Label ID="lblComment" runat="server" Text="Comment:" Font-Size="X-Large"></asp:Label>
<br style="font-size: x-large" />
<textarea id="taComment" ></textarea>
<br style="font-size: x-large" />
<asp:Label ID="lblCommentComment" runat="server" Text="Comment specific for the physical place" Font-Size="Medium"></asp:Label>
<br style="font-size: x-large" />
<br style="font-size: x-large" />
<asp:Button ID="btSaveLocation" runat="server" Text="Save current location as new place" OnClick="btSaveLocation_Click" Font-Size="XX-Large" Height="50px" />
</form>
<script hidden="hidden">
var x = document.getElementById("Comment");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
document.getElementById("lblCoordinates").textContent += "Your location in Coordinates is: ";
document.getElementById("lblLat").innerHTML = position.coords.latitude;
document.getElementById("lblLon").innerHTML = position.coords.longitude;
document.getElementById("iFrame").src = "https://www.google.com/maps/embed/v1/place?key=<key>&q=" + latlon + "&maptype=satellite";
document.getElementById("iFrame").hidden = "";
}
function showError(error) {
switch (error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>
</body>
</html>
When I click the first button, the two labels are getting filled out with the latitude and longitude as they are expected to.
When I click the button "Save current location as new place" it executes the following code in C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
namespace BeeMaster
{
public partial class CreatePlace : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btSaveLocation_Click(object sender, EventArgs e)
{
string lat = lblLat.Text;
string lon = lblLon.Text;
}
}
}
As you see, there is nothing in the Page_Load function, but still it seems to somehow reset the labels to their inital state because when I debug the application during run time and set a breakpoint at the beginning of the btSaveLocation_Click function then I see that the text of the two labels is blank already.
Does anybody know please what the problem is here?
Thanks

The content of a label is not part of a postback and thus will not be updated in the viewstate. Put your values in two hidden fields and use those to communicate with the server logic.

I found the solution. There were actually two problems:
The two labels that I was referring to in the codebehind file were not part of the form, they were in fact outside the form.
In the codebehind file I had to request their value in the Page_Load function and not in the function of the button.
This actually solved the problem.
Thanks everybody

Related

Unable to use html controls from code behind

I am using html tags and I have written some code on code behind but it is not picking the values given to id. Infact it says the 'FileUpload1' does not exist in the current context. I do not want to use asp controls at all. I have heard adding runat = "server" does the thing but still cannot find the id's. What am I doing wrong?
<div id="mainContent">
<div class="column" id="colFull">
<div class="contentSection">
<div id="progress" style="display: none">
<img alt="Loading .." src="../../../Images/ajax.gif" />
</div>
<table width="100%">
<tr>
<td class="label" style="width:15%">
Upload File
</td>
<td class="description" >
<input type="file" id="FileUpload1" runat="server"
class="largeTextField" onclick="Upload" multiple="multiple"
style="width:260px;"/>
<input type="button" id="btnUpload"
runat="server" value="Upload" />
</td>
</tr>
</table>
mycodebehind:
public partial class PgPracFileUploader : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Upload(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "insert into tblFiles values (#Name, #ContentType, #Data)";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#Name", filename);
cmd.Parameters.AddWithValue("#ContentType", contentType);
cmd.Parameters.AddWithValue("#Data", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
}
It says FileUpload1 does not exist in the current context.
Try to change:
<input type="file" id="FieUpload1" runat="server" class="largeTextField" onclick="Upload" multiple="multiple" style="width:260px;"/>
to
Id Must be same as you are using in the .cs page
\/\/\/\/
<input type="file" ID="FileUpload1" runat="server" class="largeTextField" onclick="Upload" multiple="multiple" style="width:260px;"/>
As stated here your id attribute is case sensitive so you are using id then the server will just serve it up as it is in your page, but if you used ID then the server will be serve that control as a asp.net control.

How to create single page search form with ajax in MVC Razor

I'm a beginner in the ways of MVC / Razor... Basically I have 2 pages just for showing a search result from an API that I'm consuming with Json.
Index.cshtml: (Just a form)
#model ConsultaInterna.Models.SearchApi
<div class="jumbotron">
<h2>Consulta Interna</h2>
Placa
#using (Html.BeginForm("Search", "Home"))
{
<input asp-for="Model.Name" class="form-control" name="name" id="txtName" />
<input class="form-control" type="submit" id="ok" />
}
and Search.cshtml (Which also have the form. I want to leave just this page, right now I can't because if I load directly from Search.cshtml it gives me an error like
"Unexpected character encountered while parsing value: <. Path '', line 0, position 0. " (Obviously because I'm trying to load labels with a null search)
this is Search.cshtml
#model ConsultaInterna.Models.SearchApi
<div id="loader" class="spinner" style="display:none">OIE</div>
<div class="header formPesquisa">
#using (Ajax.BeginForm("Search", new AjaxOptions()
{
HttpMethod = "POST",
LoadingElementId = "loader",
UpdateTargetId = "resultado"
}))
{
<input placeholder="Placa" asp-for="Model.Name" name="name" id="txtName" width="30" />
<input class="pesquisa" type="submit" id="enviar" value="Ok" />
}
<div class="panel">Placa #Model.Name</div>
<div class="panel">Last Name / Model.LastName</div>
ALSO Important, the Ajax form isn't working properly... the loader won't show up.
You need to move your loader div into the Ajax.BeginForm.
You need also need to add the resultado div to display your result.
#using (Ajax.BeginForm("Search", "Home", new AjaxOptions()
{
HttpMethod = "POST",
LoadingElementId = "loader",
UpdateTargetId = "resultado"
}))
{
<div id="loader" class="spinner" style="display:none">OIE</div>
<input placeholder="Placa" asp-for="Model.Placa" class="pesquisa placa" maxlength="7" name="placa" id="txtPlaca" width="30" />
<input placeholder="CPF" asp-for="Model.CPF" class="pesquisa cpf" maxlength="11" name="cpf" id="txtCPF" />
<input class="pesquisa" type="submit" id="enviar" value="Enviar" />
<div id="resultado"></div>
}
<div class="panel">Placa #Model.Name</div>
<div class="panel">Last Name / Model.LastName</div>
</div>
You also need to make sure you have added the relevant reference to the specific unobtrusive ajax library. As an example:
BundleConfig
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive-ajax.min.js",
"~/Scripts/jquery.validate*"));
_layout.cshtml
#Scripts.Render("~/bundles/jqueryval")
Example controller action
[HttpPost]
public ActionResult Search(string placa, string cpf)
{
return new JsonResult { Data = "found", JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

Partial page updating using update panel

I am creating "edit my profile page" where I have some text boxes and drop down lists.I have a requirement such that when I select a value in my first drop down, the second drop down should fill. But this is not happening.
<asp:UpdatePanel runat="server" ID="updatepanel1" UpdateMode="Conditional">
<ContentTemplate >
<asp:Label runat="server" Id="lbljobIndus" Text="Preferred Job Industry" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<span style="color: black; font-family: Calibri; font-size: small">:</span>
<asp:Label runat="server" ID="lblPreferredJobIndustry" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="tbPreferredJobIndustry" runat="server" Height="19px" OnSelectedIndexChanged="ddlTargetedIndustry_SelectedIndexChanged">
<asp:ListItem Selected="True" Value="-1">--Select Industry--</asp:ListItem>
<asp:ListItem Value="1">Administration</asp:ListItem>
<asp:ListItem Value="2">Hospital/HealthCare</asp:ListItem>
<asp:ListItem Value="3">Medical Transcription</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<br />
<asp:Label runat="server" ID="lblJobCat" Text="Preferred Job Category" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<span style="color: black; font-family: Calibri; font-size: small">:</span>
<asp:Label runat="server" ID="lblJobCategory" Font-Names="Calibri" Font-Size="Small" ForeColor="Black"></asp:Label>
<asp:DropDownList ID="tbJobCategory" runat="server">
<asp:ListItem Selected="True" Value="-1">-Position Category-</asp:ListItem>
</asp:DropDownList>
<br />
<br />
</ContentTemplate>
</asp:UpdatePanel>
This is the code to populate the second drop down list :-
protected void ddlTargetedIndustry_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlDataAdapter myda = new SqlDataAdapter("Select s_CategoryName,FK_TargetedIndustryID FROM [OfinityJobSearch].[dbo].[tm_JobCategory] where FK_TargetedIndustryID='" + tbPreferredJobIndustry.SelectedItem.Value + "'", con);
myda.Fill(ds);
tbJobCategory.DataSource = ds;
tbJobCategory.DataValueField = "FK_TargetedIndustryID";
tbJobCategory.DataTextField = "s_CategoryName";
tbJobCategory.DataBind();
tbJobCategory.Items.Insert(0, new ListItem("--Select Job Category--", "0"));
}
I used update panel so that the values in other text boxes will not get cleared on the post back. But right now, I think the post back is not happening.Can you please check my code and tell me where the error is?
Set AutoPostBack= true for the first ddl
U can use AjaxToolkit CascadingDropDown it's very helpful and useful. But in case of CascadingDropDown u need additional service.
<ajaxToolkit:CascadingDropDown ID="CDD1" runat="server"
TargetControlID="DropDownList2"
Category="Model"
PromptText="Please select a model"
LoadingText="[Loading models...]"
ServicePath="CarsService.asmx"
ServiceMethod="GetDropDownContents"
ParentControlID="DropDownList1"
SelectedValue="SomeValue" />
UPDATE:
Full example here
your *.aspx
<asp:DropDownList ID="DropDownList1" runat="server" Width="170" />
<asp:DropDownList ID="DropDownList2" runat="server" Width="170" />
<ajaxToolkit:CascadingDropDown ID="CascadingDropDown1" runat="server" TargetControlID="DropDownList1"
Category="Make" PromptText="Please select a make" LoadingText="[Loading makes...]"
ServicePath="CarsService.asmx" ServiceMethod="GetDropDownContents" />
and add code to page
[WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static CascadingDropDownNameValue[] GetDropDownContentsPageMethod(string knownCategoryValues, string category)
{
return new CarsService().GetDropDownContents(knownCategoryValues, category);
}
add web service
<%# WebService
Language="C#"
CodeBehind="~/App_Code/CarsService.cs"
Class="CarsService" %>
Code for service
[System.Web.Script.Services.ScriptService]
public class CarsService : WebService
{
// Member variables
private static XmlDocument _document;
private static Regex _inputValidationRegex;
private static object _lock = new object();
// we make these public statics just so we can call them from externally for the
// page method call
public static XmlDocument Document
{
get
{
lock (_lock)
{
if (_document == null)
{
// Read XML data from disk
_document = new XmlDocument();
_document.Load(HttpContext.Current.Server.MapPath("~/App_Data/CarsService.xml"));
}
}
return _document;
}
}
public static string[] Hierarchy
{
get { return new string[] { "make", "model" }; }
}
public static Regex InputValidationRegex
{
get
{
lock (_lock)
{
if (null == _inputValidationRegex)
{
_inputValidationRegex = new Regex("^[0-9a-zA-Z \\(\\)]*$");
}
}
return _inputValidationRegex;
}
}
/// <summary>
/// Helper web service method
/// </summary>
/// <param name="knownCategoryValues">private storage format string</param>
/// <param name="category">category of DropDownList to populate</param>
/// <returns>list of content items</returns>
[WebMethod]
public AjaxControlToolkit.CascadingDropDownNameValue[] GetDropDownContents(string knownCategoryValues, string category)
{
// Get a dictionary of known category/value pairs
StringDictionary knownCategoryValuesDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
// Perform a simple query against the data document
return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(Document, Hierarchy, knownCategoryValuesDictionary, category, InputValidationRegex);
}

How can I use a json member object in dojo widget

I am iterating a json whose format is like this
request("js/my/data/sample.json", {
handleAs: "json"
}).then(function (jsonResults) {
arrayUtil.forEach(jsonResults.LinksMap, function (List) {
arrayUtil.forEach(List.LinksMap.entry, function (Ientry) {
var widget = new support(Ientry.Link).placeAt(authorContainer);
});
});
});
The Widget HTML template looks like
<div><span title="${title}">${title}</span></div> <br />
<div><span title="${description}">${description}</span></div> <br />
<a class="info" title="${title}" href="${url}">${title}</a><br />
I would like to use the object linkType provided in json to use a different class in the html template of the widget so if it linkType is "information" then use
<a class="info" title="${title}" href="${url}">${title}</a><br />
If it is news then use
<a class="news" title="${title}" href="${url}">${title}</a><br />
A combination of this modified template:
<div><span title="${Link.title}">${Link.title}</span></div> <br />
<div><span title="${Link.description}">${Link.description}</span></div> <br />
<a class="${className}" title="${Link.title}" href="${Link.url}">${Link.title}</a><br />
and this modified code should do the trick:
request("js/my/data/sample.json", {
handleAs: "json"}).then(function(jsonResults){ arrayUtil.forEach(jsonResults.LinksMap, function(List){arrayUtil.forEach(List.LinksMap.entry, function(Ientry){
if('information' === Ientry.linkType) Ientry.className = 'info';
else if('news link' === Ientry.linkType) Ientry.className = 'news';
var widget = new support(Ientry).placeAt(authorContainer);
});});});
But a much better idea would be implementing a postCreate method in your widget that would be able to modify widget in any way you like, after it gets constructed and just before it gets displayed.
Please refer to this guide and search for postCreate there.

required field validator not working with html editor

I have a text box using cc1:Editor and when I place a required field validator on it, it displays as soon as the page loads. How can I hide the error and allow it to display only if the html editor box is empty?
<code><cc1:Editor ID="txtDescription" Width="500px" Height="525px"
runat="server" TextMode="SingleLine" /></code>
<code>
<asp:RequiredFieldValidator ID="rfvDescription" runat="server"
ControlToValidate="txtDescription"
ErrorMessage="Must include Description" Font-Bold="True"></asp:RequiredFieldValidator>
</code>
<code><asp:Button ID="SubmitBtn" runat="server"
Text="Submit" OnClick="SubmitBtn_Click" class="form-td" Height="30px" />
<script language="javascript" type="text/javascript">
document.onkeypress = keyhandler;
function keyhandler(e) {
Key = window.event.keyCode; if (Key == 13) {
var obj = document.getElementById('<%=SubmitBtn.ClientID%>');
obj.focus();
obj.click();
}
}
</script>
Yes, you can perform custom validation on your submit button client side & server side validation on your postback event thus removing required field validator. Check following example:
On your aspx page
<p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="javascript:return ValidateEditor();"
ValidationGroup="myGroup" onclick="Button1_Click" />
<br />
</p>
<asp:Label ID="lblMessage" runat="server" ForeColor="Red"></asp:Label>
<cc1:Editor ID="Editor1" runat="server" />
<script type="text/javascript">
function ValidateEditor() {
var txtEditor = $find('<%=Editor1.ClientID %>');
if (txtEditor.get_content() == null || txtEditor.get_content() == '') {
alert('Text cannot be empty');
document.getElementById('<%=lblMessage.ClientID %>').innerHTML='Text cannot be empty';
return false;
}
else
return true;
}
</script>
On server side
if (string.IsNullOrEmpty(Editor1.Content.ToString()))
{
lblMessage.Text = "Text cannot be empty";
}
else
{
// Do your work here
}