required field validator not working with html editor - requiredfieldvalidator

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
}

Related

ASP.NET Button onklick resets label text

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

VB.net OnClientClick pass in ID of another div

I have the following asp repeater:
<asp:Repeater runat="server" ID="rptResults">
<ItemTemplate>
<div class="FileFile Large pdf SearchResult" id="<%# DirectCast(Container.DataItem, FileFolder).DocStoreID%>">
<a href='<%# DirectCast(Container.DataItem, FileFolder).Link %>' style="text-decoration:none">
<%# DirectCast(Container.DataItem, FileFolder).BackgroundHTML%>
<p style="float:left;line-height:32px;margin:0px"><%# DirectCast(Container.DataItem, FileFolder).Filename%></p>
</a>
<asp:Button runat="server" OnClientClick="return confirmation(this);" ID="btnDeleteFile" CommandArgument="<%# DirectCast(Container.DataItem, FileFolder).DocStoreID%>" UseSubmitBehavior="false" Text="Delete" Style="float:right;margin-top:8px;cursor:pointer;"/>
<a style="float:right;line-height:32px;margin-right:10px">ID = <%# DirectCast(Container.DataItem, FileFolder).DocStoreID%></a>
</div>
</ItemTemplate>
</asp:Repeater>
<script>
function confirmation(sender) {
if (confirm("Delete file "+ sender.id + "?"))
return true;
else return false;
}
</script>
I want the OnClientClick to say:
Delete File ######
to do this I need to pass in the id of the parent div, or the content of the <a> next to it.
Currently, I have OnClientClick="return confirmation(this);", which passes in the button. SO I could possibly store this information in a field on the button, but I have tried:
name="%# DirectCast(Container.DataItem, FileFolder).DocStoreID%>"
But this does not work. Are there any other variables I can use to store this, or a way to pass a reference to another element within the repeater?
you can use title attribute in your button:
title="<%# DirectCast(Container.DataItem, FileFolder).DocStoreID%>"
and then your javascript will be
function confirmation(sender){
if(confirm("Delete file " + sender.title + " ?"))
return true;
else
return false;
}
be aware that title attribute is intended to display a tooltip, so the user will see a toolip over your button. Hope it helps.
Try this
OnClientClick="return confirmation('<%= DirectCast(Container.DataItem, FileFolder).DocStoreID %>');"
And you JS would be
function confirmation(sender) {
if (confirm("Delete file "+ sender + "?"))
return true;
else return false;
}

Change style of an item inside updatepanel dynamically

I have an image inside an updatepanel. When I click on the image it needs to be highlighted. I use addclass and removeclass to make this work, if it is outside updatepanel. When I put the image inside the updatepanel, the css is applied but then reverts to original after the update completes and the page is rendered.
How can I change the styling of the image inside the updatepanel dynamically?
Markup:
<asp:UpdatePanel ID="UpdatePanel2" runat="server" class="journey-categories">
<ContentTemplate>
<ul class="journey-categories">
<asp:Repeater ID="rptJourneyCategories" runat="server">
<ItemTemplate>
<li>
<a href="javascript:void(0)" data-categoryid="<%# Eval("Id") %>" data-introtitle="<%# Eval("IntroTitle") %>" data-introtext="<%# Eval("IntroText") %>">
<img class="thumb" src="<%# Eval("CategoryIcon") %>" width="70" height="70" alt="" id="imgCategoryIcon" />
</a>
<span><%# Eval("Title") %></span>
</li>
</ItemTemplate>
</asp:Repeater>
</ul>
</ContentTemplate>
</asp:UpdatePanel>
Jquery:
$('[data-categoryid]').off('click.categories').on('click.categories', function () {
$(this).closest('ul').find('li.selected').removeClass('selected');
$(this).parent().addClass('selected');
});
I got this to work with the help of EndRequestHandler
I added the following inside script document ready and it updated the styling after the update panel completed.
<script type="text/javascript">
$(function () {
var onDomReady = function () {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function EndRequestHandler() {
var type = $('[id$=ddlType]').val();
$('a[data-categoryid="' + type + '"').parent().addClass('selected');
}
}});

Validate dynamically created fields when one is changed

I have a program that dynamically creates various text boxes / drop down lists. I am trying to figure out how to validate these fields only when one is changed. Basically if someone entered a date in the text box then I need the program to validate that the drop down list was changed or vice versa. If there are no changes to both fields then it should not validate. Any help would be extremely appreciated. Here is the code:
<asp:TemplateField HeaderText="ValidatedDate" SortExpression="ValidatedDate">
<EditItemTemplate>
<asp:TextBox ID="txtValDate" Width="100px" MaxLength="10" runat="server" AutoPostBack="true"
Text='<%# Bind("ValidatedDate","{0:MM/dd/yyyy}") %>'></asp:TextBox>
<asp:RegularExpressionValidator ValidationGroup="g1" ID="RegularExpressionValidator10"
runat="server" ControlToValidate="txtValDate" Display="None" ErrorMessage="Validated Date: ##/##/####"
ValidationExpression="\d{1,2}/\d{1,2}/\d{4}"></asp:RegularExpressionValidator>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblValidatedDate" runat="server" Text='<%# Bind("ValidatedDate","{0:MM/dd/yyyy}")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ProductStatus" SortExpression="ProductStatusDescription">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList4" runat="server" DataSourceID="SqlDataSource6" AutoPostBack="true"
DataTextField="StatusDescription" DataValueField="StatusID" SelectedValue='<%# Bind("Status") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblProductStatus" runat="server" Text='<%# Bind("ProductStatusDescription")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
My apologies, the code can be a bit confusing without the correct context.
ebyrob, thank you for your help. I figured it out however and it works beautifully. Here is the code that fixed it all:
protected void AddError(string errorMessage)
{
cstValidate.IsValid = false;
cstValidate.ErrorMessage = errorMessage;
cstValidate.EnableClientScript = false;
}
protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtValidatedDate = GridView2.Rows[e.RowIndex].FindControl("txtValDate") as TextBox;
DropDownList ddlStatusCompare = GridView2.Rows[e.RowIndex].FindControl("dropdownlist4") as DropDownList;
if (txtValidatedDate.Text == string.Empty && ddlStatusCompare.SelectedValue == "1")
{
AddError("Please enter a Validated Date");
e.Cancel = true;
}
else if (txtValidatedDate.Text != string.Empty && ddlStatusCompare.SelectedValue == "0"
|| txtValidatedDate.Text != string.Empty && ddlStatusCompare.SelectedValue == "99")
{
AddError("Please remove the Validated Date");
e.Cancel = true;
}
if (!e.Cancel)
Helpers.LogChanges(GridView2, e, _employeeID, "SaleProducts");
}

updatepanel does not trigger repeater itemcommand

I just want to trigger the LinkButton in a repeater which has a OnItemCommand. But the page do post back. Here is my code:
<asp:UpdatePanel ID="recommendedAdvertsUpPnl" runat="server">
<ContentTemplate>
<div class="tagList">
<asp:Label ID="lbListBookType" runat="server"></asp:Label>
<asp:Repeater ID="rpRecommendedAdvertFacultyList" runat="server" OnItemDataBound="rpRecommendedAdvertFacultyList_ItemDataBound" OnItemCommand="rpRecommendedAdvertFacultyList_ItemCommand">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate>
<asp:LinkButton ID="lbtnAdvertFaculty" runat="server" CommandArgument='<%#Eval("facultyId") %>' CommandName="selectFaculty" CssClass="advertFacultySelection"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater>
</div>
<div class="RecommendedAdverts_List">
<asp:Repeater ID="rpRecommendedAdvertList" runat="server" OnItemDataBound="rpRecommendedAdvertList_ItemDataBound">
<HeaderTemplate>
<ul class="content_recommended">
</HeaderTemplate>
<ItemTemplate>
<%# Container.ItemIndex % 4 == 0 ? "<li><div class=advertContainer>": String.Empty%>
<div class="advertPanel">
<div class="rAdvPanel">
<div class="advertPic"><asp:Panel ID="pnlRecAdvertPic" runat="server"></asp:Panel></div>
<div class="advertInfoPanel">
<%#Eval("Book.Name")%> <br />
<%#Eval("Book.Authors")%><br />
<%#Eval("Price")%> TL<br />
</div>
</div>
</div>
<%# Container.ItemIndex % 4 == 3 ? "</div></li>": String.Empty%>
</ItemTemplate>
<FooterTemplate>
</div></li>
</ul>
</FooterTemplate>
</asp:Repeater>
</div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rpRecommendedAdvertFacultyList" EventName="ItemCommand" />
</Triggers>
</asp:UpdatePanel>
There is no problem except for triggering. Here is the my server side code:
protected void rpRecommendedAdvertFacultyList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
AdvertFacultyInfo item = (AdvertFacultyInfo)e.Item.DataItem;
LinkButton lbtnAdvertFaculty = (LinkButton)e.Item.FindControl("lbtnAdvertFaculty");
lbtnAdvertFaculty.Text = item.Faculty.name;
}
}
protected void rpRecommendedAdvertFacultyList_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch (e.CommandName)
{
case "selectFaculty":
List<AdvertFacultyInfo> advFacultyInfoList = EntitiyProvider.GetAdvertFacultyInfoListByFacultyId(Convert.ToInt32(e.CommandArgument));
List<Advert> selectedList = new List<Advert>();
foreach (AdvertFacultyInfo item in advFacultyInfoList)
{
Advert currentAdv = this.recommendedAdvertList.FirstOrDefault(i => i.id == item.advertId);
if ( currentAdv != null)
{
selectedList.Add(currentAdv);
}
}
rpRecommendedAdvertList.DataSource = selectedList;
rpRecommendedAdvertList.DataBind();
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", "<script type='text/javascript'>$('.content_recommended').quickPager()</script>", false);
break;
default:
break;
}
}
I have also tried this code: But it gives error like lbtnAdvertFaculty could'nt find
<asp:AsyncPostBackTrigger ControlID="lbtnAdvertFaculty" EventName="Click" />
I have researched a lot of document written about this problem but I could not find useful examples and solution.
Best Regards.
try putting ClientIDMode="AutoID" to #page directive