asp.net web forms using variables inside a server control - c#

I am trying to use a variable inside server control in asp.net webform page(.aspx). I am getting syntax error. What may be the issue?
<%string msgCancelProject = "You are not authorized to cancel the project."; %>
<asp:Button ID="CancelProject" <%if(IsAuthorized){%> title="<% =msgCancelProject %>" clickDisabled="disable" <%}%> runat="server" Text="Cancel Project" 
                     OnClick="btnCancelProject_Click" 
                    OnClientClick="return confirm('Are you certain you want to cancel the record?');" />

It's not possible to do what you are trying to do with a server control. I.e. adding a property dynamically in markup. You can only set property values but that's not what you want.
You could achieve what you want from the code behind as follows.
Keep your markup like this.
<asp:Button ID="CancelProject" runat="server" Text="Cancel Project" OnClick="btnCancelProject_Click"
OnClientClick="return confirm('Are you certain you want to cancel the record?');" />
And, in your code behind do this.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string msgCancelProject = "You are not authorized to cancel the project.";
if (IsAuthorized)
{
CancelProject.Attributes.Add("title", msgCancelProject);
CancelProject.Attributes.Add("clickDisabled", "disable"); // I'm not sure what you are trying to do here
}
else
{
CancelProject.Attributes.Remove("title");
CancelProject.Attributes.Remove("clickDisabled");
}
}
}
Hope this helps.

Related

show html elements based on user's role

I am trying to hide html elements from plain users such that only users.
I have simple asp.net web form setup that makes use of roles provider and membership.
<li runat="server" id="li1" visible ='<%# HttpContext.Current.User.IsInRole("admin") %>'><span> Admin link</span></li>
I also am trying this without success:
<li runat="server" id="liAdminUsers" visible ='<%# isAdmin %>'><span> The Hopper</span></li>
the code behind is:
public bool isAdmin =false;
protected void Page_Load(object sender, EventArgs e)
{
isAdmin = Page.User.IsInRole("admin");
}
update: I know I can get it working by adding in the code behind:
liAdminUsers.Visible = false ;
but want a UI solution in the .aspx code
You are using data-binding syntax <%# ... %>, so you need to call Page.DataBind()
You typically call DataBind() in your Page_Load method.
I once did something similar using a custom XML file with an attribute indicating if roles were applied or not for a particular application link - and if so, another attribute containing the role name. The code-behind would then check the custom membership store using the logged-in users network identity for authorization checking.
Write a static method in code behind to test the role
public static bool IsAdmin(){
//chech and return true or false
}
In html call this method like
<li runat="server" id="liAdminUsers" visible ='<%# isAdmin() %>'>.....</li>
In this way you can control you logic like any other method.
Or you can directly set element visible false in your code behind
public static void IsAdmin(){
var admin = ....; //check current user role;
liAdminUsers.Visible = admin;
}
I suggest you formulate a class that will hide the said elements.
CSS
hide-elements {
display:none;
}
show-elements {
display:block;
}
C# CodeBehind
public string isAdmin()
{
if (condition == false)
return "hidden-elements";
else
return "show-elements";
}
HTML code
<li runat="server" id="liAdminUsers" class='<%# isAdmin() %>'>.....</li>
Hope this help. :D (my first post)
If you are reaching a variable from code behind, you need to use <%= isAdmin%> , not <%# isAdmin()%>
I had a similar issue earlier and I solved it by declaring a protected variable in .aspx.cs file and directly using it in the aspx page.
Aspx Page:
<li runat="server" id="li1" visible ='<%# IsAdmin %>'>
<span> Admin link</span>
</li>
Aspx.cs File:
protected bool IsAdmin = false;
in aspx files you can try :
<% if (isAdmin()==true ) { %>
your html codes and server controlls
<%}>
if isAdmin retruns true asp write yours codes in (your html codes and server controlls) your page.

Check li click value

I m using two list items with link. Now I want to check which link was clicked from the client side. Here is my code:
<ul id="navtabs">
<li id="basic" runat="server" class="cat-item cat-item-6 current-cat">new</li>
<li id="new" runat="server" class="cat-item cat-item-8">old</li>
</ul>
I want to check which item am click whether basic or new
if(this.basic.clicked ==true)
{
do something
}
else
{
do something
}
How can I do this?
If you are suing Web forms then,
The the control which are suing must be server control
If it is a link the put runat="server" and id of the control
Create on click event of every link.
But what is the purpose of those link is not clear.
What action do you want to take on the click must be clear.
I have a trick for it. You can do this with help of jQuery, one hidden field & one hidden asp button.
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Hidden Button" />
<asp:HiddenField ID="hdnLIClicked" runat="server" />
Now jQuery part, in ready event
$().ready(function() {
$("#Button1").hide();//hiding the button through jQuery
$("#basic").click(function(){
$("#hdnLIClicked").val("basic");
$("#Button1").click();
});
$("#new").click(function(){
$("#hdnLIClicked").val("new");
$("#Button1").click();
});
});
Or you can give a common class to all your list items, if there are more list items, like you already have a common class for both of your list items. i.e "cat-item".
$().ready(function() {
$("#Button1").hide();//hiding the button through jQuery
$(".cat-item").click(function(){
$("#hdnLIClicked").val($(this).attr("id"));
$("#Button1").click();//this will fire the hidden button event on server side.
});
});
And you'll have which 'li' was clicked in the hiddenfield.
On backend, handle the button click event like this.
protected void Button1_Click(object sender, EventArgs e)
{
if (hdnLIClicked.Value == "basic")
{
//handle your logic for basic here...
}
else if (hdnLIClicked.Value == "new")
{
//handle your logic for new here...
}
}
Hide the button through jQuery, don't set its property Visible="false", or the button won't get rendered on client side.
Enjoy ;)...

use code behind to pop aspx confirmation message

I need to return a confirmation message to OnClientClick event. The problem is I have to get the message from stored procedure, and I don't seem to call my function right.
<asp:ImageButton
OnClientClick="return confirm(<%# GetConfirmExportMessage()%>);"
OnClick="btnExportRed_Click"
runat="server"
ImageUrl="~/Images/excel_red.gif"
ID="btnExportRed"
AlternateText="Export all records!"/>
My code behind:
public string GetConfirmExportMessage()
{
string xmlFilterForExport = Parameters.ToString().Split('+')[4].Trim();
string alertMessage = companiesSearcher.GetAlertMessage(xmlFilterForExport, 1, null, null, IdSegment, 1, Convert.ToInt32(RoDB2004.BLL.clsUsers.UserID));
return alertMessage;
}
Try using equal sign instead of pound (and don't forget your single quotes).
OnClientClick="return confirm('<%= GetConfirmExportMessage()%>');"
However, if you're ImageButton is located inside a DataGrid or GridView, the server-side code will not be evaluated and will yeield an alert saying <%= GetConfirmExportMessage()%> instead of the real message.
To get around this problem (and to increase performance, throughput, etc.), output your message once to a variable, then alert the contents of the variable.
<script language="JavaScript">
var myMessage = '<%= GetConfirmExportMessage()%>';
</script>
Later, in the GridView...
OnClientClick="return confirm(myMessage);"
You save throughput by repeating a small variable name like "myMessage" and avoid repeating some big message. Also note, that the method GetConfirmExportMessage isn't called dozens of times increasing performance.
If your message is specific to data within a current row and not static like "Are you sure?", then I suggest you perform this operation inside the GridView's RowDataBound event. You'll have full access to the ImageButton and to the data the current row is binding to, which makes it very easy to setup server-side. Check out the FindControl() method, or if you know the exact location, just reference it and unbox the object.
protected void gvMyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton ibtn = (ImageButton)e.Row.FindControl("btnExportRed");
if(ibtn != null)
{
ibtn.ClientClick = "return confirm('" + GetConfirmExportMessage() + "');";
}
}
}
As an alternative solution, maybe you should look into WebMethods, AJAX and jQuery. This solution is probably the better one because the data is not sent to the client and only retrieved when necessary.
you need to wrap your confirm in '
<asp:ImageButton
OnClientClick="return confirm('<%# GetConfirmExportMessage()%>');"
OnClick="btnExportRed_Click"
runat="server"
ImageUrl="~/Images/excel_red.gif"
ID="btnExportRed"
AlternateText="Export all records!"/>
You probably want
OnClientClick="return confirm('<%= GetConfirmExportMessage()%>');"
Note that this will be populated when the page is rendered, not when the button is clicked, so you may as well use
btnExportRed.OnClientClick = "javascript:return confirm('" + GetConfirmExportMessage() + "');"
in your code behind.

Client-side validation is not firing on my custom BaseValidator

So, I'm writing a custom validator to validate the Ajax Toolkit's Rating control. The client side validation isn't firing, though.
I have this method to register the script:
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string script = #"<script type=""text/javascript"">function RatingValidatorEvaluateIsValid(val)
{
alert( 'here' );
return false;
}</script> ";
Page.ClientScript.RegisterClientScriptBlock(GetType(), "ratingValidator", script);
}
And I register the attribute like this:
protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
{
base.AddAttributesToRender(writer);
// Add the client-side code (if needed)
if (this.RenderUplevel)
{
writer.AddAttribute("evaluationfunction", "RatingValidatorEvaluateIsValid", false);
}
}
The script appears on the page, as well as the attribute, but the alert('here') never appears.
(Everything works fine, Server-side)
Edit Markup:
<ajaxToolkit:Rating ID="ajaxRating" runat="server" StarCssClass="ratingStar" WaitingStarCssClass="savedRatingStar"
FilledStarCssClass="filledRatingStar" EmptyStarCssClass="emptyRatingStar" CssClass="stars"
RatingAlign="Horizontal" RatingDirection="LeftToRightTopToBottom"
AutoPostBack="True" OnChanged="OnChanged" />
<my:RatingValidator runat="server" ID="RatingValidator" ControlToValidate="ajaxRating"
ErrorMessage="Please select a rating." EnableClientScript="True"
</my:RatingValidator>
Edit 2 Okay, this is weird...
The span that gets generated is proper:
<span id="CPHUser_rating_RatingValidator" evaluationfunction="RatingValidatorEvaluateIsValid" style="visibility:hidden;">Please select a rating.</span>
But the JS at the bottom doesn't have my evaluationfunction assigned.
var CPHUser_rating_RatingValidator = document.all ? document.all["CPHUser_rating_RatingValidator"] : document.getElementById("CPHUser_rating_RatingValidator");
CPHUser_rating_RatingValidator.controltovalidate = "CPHUser_rating_ajaxRating";
CPHUser_rating_RatingValidator.errormessage = "Please select a rating.";
Looks like I answered my own question...
I was apparently assigning my evaluationfunction incorrectly.
I've changed it to this:
Page.ClientScript.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "RatingValidatorEvaluateIsValid");
and now it works.
Thanks for your help, guys!

ASP, Listview conditional Alert

I'm currently working with a listview in which I want an htmltablecell to possess the onclick property which is driven by the codebehind rather than a javascript.. However I'm guessing that's pretty much a dream getting it to obey the C# code... Anyways this is what I want it to run:
protected void show_anm(object sender, EventArgs e)
{
Label hiddenc = (Label)listview1.FindControl("hidden");
Alert.Show(hiddenc.Text);
}
and here's the Alert class
public static class Alert
{
public static void Show(string message)
{
string cleanMessage = message.Replace("'", "\\'");
string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
Page page = HttpContext.Current.CurrentHandler as Page;
if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
{
page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
}
}
}
The point is creating a listview with a two conditional tablecells, one which appears only when a certain condition is met and the other appears every other time (that's alredy sorted out). Where the one demanding a condition is Clickable, and upon clicking it it'll display an Alertbox with Data from a specific DB cell...
Sorry if my language and the question seemes off, English isn't my native language and I haven't doused myself in Coffe yet.
Any help on the matter would be most appritiated
EDIT1*
<asp:Listview ................
<ItemTemplate>
<tr ......>
<td id=default .....>
<asp:label ........ Text='<%# eval("stuff") %> />
</td>
<td id=conditional onclick=alert()..........>
<asp:label ......... Text='<%# eval("stuff") %> />
</td>
<td id=hidden visible=false ...........>
<asp:label ......... Text='<%#eval("stuff i want in alert") %>' />
.....
<script tyupe="text/javascript">
function alert()
{
var msg = document.getElementById("tried with label id and tablecell id nothing seemingly worked").value;
alert(msg);
}
</script>
I recently made a workaround that shows the data I want to display in the labels tooltip but I'd still prefer the alertbox to work properly as it feels more natural to click something.
Edit2 In case anyone is wondering I used the ItemDataBound event to bind the visibility of cells default and conditional within an if clause to make sure the control exists and the conditions are met.
I am confused as to why you're doing what you're doing. Why do you want the codebehind to handle an onclick event of a htmltablecell when you are pumping out javascript to show an alert anyway?
Why not just handle the whole logic within Javascript?
A postback from a htmltablcell will also require javascript
Set your tablecell to call a javascript function which would obtain the alert text from the hidden value and display that;
function ShowAlert()
{
var message = document.getElementbyId("hidden").value;
alert.show(message);
}

Categories