Pass values to javascript in ASP.NET - c#

I have an ASP textbox control where I need to execute some javascript function when the OnClick event occurs. I need to pass to that javascript function two IDs of other controls on that page. My textbox markup is as follows:
<asp:TextBox ID="txtMonthDisplay" runat="server" Style="border-top: none; border-left: none;
border-right: none; border-bottom: solid 1px blue; cursor: pointer; color: Blue;
width: 35px;" EnableViewState="True" MaxLength="3" onClick="javascript: ShowBox('<%= divYear.ClientID%>', '<%= txtYearDisplay.ClientID %>');"></asp:TextBox>
But whenever it calls the javascript function I have setup an alert to check the incoming values, and they are simply <%= txtYearDisplay.ClientID %> and <%= divYear.ClientID%>. Not the actual IDs of those controls.
What am I missing here, or doing incorrectly? I'm not well versed with asp.net so server vs. client side is a bit fuzzy for me.
Thanks

You can't Response.Write (<%= %> is shorthand for Response.Write) into a server tag (usually).
Instead, you can write your onclick handler in the codebehind:
txtMonthDisplay.Attributes["onclick"] = string.Format(
"ShowBox('{0}', '{1}');",
divYear.ClientID,
txtYearDisplay.ClientID);
By the way, you don't need the javascript: prefix. That is only necessary when setting the href of a link to execute script. It is not needed for event handlers such as onclick.

Then pass the variables from codebehind:
protected void Page_Load(object sender, EventArgs e){
txtMonthDisplay.Attributes.Add("onClick",
String.Format("ShowBox('{0}','{1}')",
divYear.ClientID,
txtYearDisplay.ClientID));
}
The <%= ... %> displaying expression is an equivalent of the embedded code block that contains only the Response.Write(…) statement. This is the simplest way to display information such as a single string, an int variable, or a constant.
Remember that the displaying expression cannot be used in the attributes of server controls. This is because the .NET Framework directly compiles the whole expression instead of the displaying content as the value to the attribute.
http://support.microsoft.com/kb/976112/en-us

Hmm, your markup looks correct, I would try a couple of things, first try adding the onclick event through code and see if the IDs get added. That way you will know if your textbox generation works correctly.
You could also work around by doing click binding after the document.ready using JQuery and having the values as hidden values on the form.

Related

onserverclick not firing for input of type date

I am building a web application in ASP.NET using webforms.
I have an input html element which I have set to run at server and I want to fire an event whenever the date is changed.
<input id="datePicker" class="form-control" style="display: inline; margin-left: 5px; width: 15%; text-align: center;" type="date" runat="server" onserverclick="Date_Changed"/>
I have the event in my codebehind:
protected void Date_Changed(object sender, EventArgs e) {}
However, the event is never fired.
Don't believe that server side click events can be wired up to a input that way (using the onserverclick).
I would consider dropping in a HTML button, say like this:
<button id="datePicker"
class="form-control"
style="display: inline; margin-left: 5px; width: 15%; text-align: center;"
type="date"
runat="server" onserverclick="Date_Changed" />
And even better yet, drop in a asp.net button.
If you drop in a input tag, then I don't think you can get the asp.net system to wire this up for you. You could I suppose write this:
(this is what a plane jane above button becomes:
<input onclick="__doPostBack('Button11','')"
name="Button11" type="button" id="Button11" value="button">
So you could try above - but using a "input" tag I don't believe will work, but try a HTML button as per above - that does allow "on server click".
Do keep in mind that if you drop in a asp.net text box, and set textmode = "date"?
Say like this:
<asp:TextBox ID="MyDateTest" runat="server" TextMode="date">
</asp:TextBox>
Then you see this:
So, above is a built in feature - you don't need any js, bootstrap, or anything at all.
but, you could add a "client" side click to your markup, as I posted a above the do post-back would (should) run your click event. However, it probably a whole lot better to not fight asp.net, since then you quite much hand coding a lot of HTML, and doing that means you quite much toss out most of the features of why you would use asp.net in the the first place (that means to take advantage of all the built in controls, and the pre-processing of those controls for you).

C# code behind for Button Click Event, ASP.NET

I'm working with HTML provided by coworker in .aspx and I need to program in .aspx.cs(C#) the functionality of the button he created using HTML.
The code I'm dealing with is as follows:
<div>
<button style="padding: 10px; margin-bottom: 10px;" class="w3-round w3-blue">Ship</button>
<button style="padding: 10px; margin-bottom: 10px;" class="w3-round w3-blue">Rate</button>
</div>
I'm new to HTML but in looking at solutions to similar questions I often see the HTML code for a functional button looking more like
<button type="submit" runat="server" id="btnLogin" class="button" onclick="btnLogin_Click();">
and sometimes with an
<asp:
at the beginning. I've tried simply adding the runat and onclick fields to the HTML that correspond with a C# method in the aspx.cs code behind but I haven't been able to make the button click actually trigger the method in the code behind. I've assumed that if I add the method with the name that follows onclick to the C# aspx.cs code then it would simply execute this upon the clicking of the button but I'm clearly mistaken.
Can I program the button's functionality in the code behind without changing the HTML provided to me? Or must I alter the HTML first and if so how?
You could probably get away with adding the runat="server" attribute to your buttons but I've never tried it and frankly, using proper web controls would be the best way to go.
Replacing them shouldn't change the look and feel of the page at all. Just add CssClass="xxx" to apply the css if there is any, otherwise they render to standard html elements anyway.
Your markup should look something like this:
<asp:Button runat="server" id="btnLogin" Text="Log In" OnClick="btnLogin_Click" />
The matching event handler in your code would look like this:
protected void btnLogin_Click(object sender, EventArgs e)
{
// Here's where you do stuff.
}
you need to replace the
onclick="btnLogin_Click();"
with
onclick="btnLogin_Click"
because the onClick property of asp.net buttons need to contain the name of the function it calls in the aspx.cs file and not the actual call.
<button type="submit" runat="server" id="btnLogin" onserverClick="btnLogin_Click1">login </button>
just replace the onClick with onserverClick
My suggestion would be to change the HTML control to <asp:Button /> and have the event handler wired up by ASP.NET. Syntax would look something like below
<asp:Button ID="Test" runat="server" Text="Button" OnClick="Test_Click" />
There are ways to reach asp.net code behind handler from html controls. You could try adding onserverclick handler or you could do a postback with arguments and add handler to the postback in contructor.
Few links to help you with it:
https://forums.asp.net/t/1650304.aspx?Calling+code+behind+function+from+a+html+button
calling server side event from html button control
If you are using a tool like Visual Studio/Express bring up the page in question (the aspx page).
From the controls toolbar drag a button over to the page.
If you double click the button in design view it will automatically create the event handler in code behind.
The button control has a couple of properties OnClick and OnClientClick. Use OnClientClick to trigger any JavaScript on the page.
Hope it helps

DNN with Telerik RadButton doesn't render Text from resource file

I hope that someone can help me with issue.
In a DNN custom module that I'm creating, I have a RadButton that doesn't show the Text value from the resource file. Other controls do read the values from the resource file.
I tried from the ascx and from the code behind. Another strange thing is that when debugging the application from the code behind I see the Text attribute.
the control definition is:
<dnn:dnnRadButton ID="CntUsSubmit" runat="server" OnClick="ProcessSendMail" resourcekey="CntUsSend"
SingleClick="true" SingleClickText="Submitting..." Style="clear: both; float: left; margin: 10px 0;" ></dnn:dnnRadButton>
inse Page_Load I make the localization (too):
CntUsSubmit.Text = Localization.GetString( "CntUsSend.Text", LocalResourceFile );
the page is rendered as:
<span id="dnn_ctr474_View_CntUsSubmit" class="RadButton RadButton_Default rbSkinnedButton"
style="clear: both; float: left; margin: 10px 0;">
<input class="rbDecorated" type="button" name="dnn$ctr474$View$CntUsSubmit_input"
id="dnn_ctr474_View_CntUsSubmit_input" value="" />
<input id="dnn_ctr474_View_CntUsSubmit_ClientState"
name="dnn_ctr474_View_CntUsSubmit_ClientState" type="hidden" />
</span>
the Sys.Application.add_init function shows:
Sys.Application.add_init(function() {
$create(Telerik.Web.UI.RadButton, {"_accessKey":"","_postBackReference":"WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions('dnn$ctr474$View$CntUsSubmit', '', true, '', '', false, true))","clientStateFieldID":"dnn_ctr474_View_CntUsSubmit_ClientState","iconData":{},"imageData":{},"singleClick":true,"singleClickText":"שולח...","toggleStatesData":[],"uniqueGroupName":"","uniqueID":"dnn$ctr474$View$CntUsSubmit","value":"שלח"}, null, null, $get("dnn_ctr474_View_CntUsSubmit"));
});
I understand the control knows the Text from the add_init, but the rendered button doesn't get the it. Can someone help me how to solve this?
I'm using DNN 7.0.2, VS 2012, for Framework 4.0
That's odd. You could try the following in its OnClientLoad event:
function OnClientLoad(sender, args)
{
sender.set_text(sender.get_text());
}
Try alerting the get_text() first to see if it retursn what you need. If so, you can put this in a global JS file and add the event handler through a Theme.
If this doesn't help try putting the desired text in a hidden field (e.g. with a unique class) and again use the set_text() method.
In the end I gave up with RadButton, instad I used Encosia's Postback Ritalin which made the trick nice and smoothly.

create a form in placeholder in C#

StringBuilder str=new StringBuilder();
str.Append("<div style='font-style:oblique;font-size:24px;text-align:left;margin-bottom:25px;'>");
str.Append("Products");
str.Append("</div>");
str.Append("<div style='font-style:oblique;font-size:18px;text-align:right;margin-bottom:25px;'>");
str.Append("<asp:TextBox ID='txtSearch' runat='server'></asp:TextBox> <asp:Button ID='btbSearch' runat='server' Text='Search'/>");
str.Append("</div>");
str.Append("<table width='100%' border='1' cellpadding='0' cellspacing='0'>");
In the second <div>, I try to create a textbox and a button and add them in the placeholder. When I debug with browser console, I see them in html code but it cannot show in the browser, it just show the table on browser. Is there any example to work these cases?
<asp: tags are entirely server side tags. They will be translated by the ASP engine into plain HTML tags.
By writing those tags to the response directly you bypass the ASP engine's ability to refactor them into proper HTML. When the browser gets them it doesn't know how to render them, so it just ignores them.
You should be creating the controls as objects, rather than as strings, for example:
TextBox txtSearch = new TextBox();
txtSearch.ID= "txtSearch";
placeHolder1.Controls.Add(txtSearch);
Button btbSearch = new Button();
btbSearch.ID = "btbSearch";
btbSearch.Text = "Search";
placeHolder1.Controls.Add(btbSearch);
Or, better yet, you could place that text in a markup file rather than using the code behind.
Most likely you are not generating ASPX page to render on server, but rather sending output of your StringBuilder to the browser. Since asp:TextBox and similar ASP.Net elements can't be rendered by browser you see nothing in a view (also nodes are present as they don't make HTML completely invalid).
You want to generate <INPUT...> elements instead of asp:TextBox to see output in browser.
Note: there are likely better way to achieve your goal (i.e. client side templates, or regular rendering in the view), but you need to spell your actual problem first.
You can use code like this
var tableBody=""; // here you have to define the table body yourself
var form=
new {
method=#"get", // decide for your request method get/post
action=#"http://www.google.com" // the page processes the request
};
var html=#"
<div style='font-style: oblique; font-size: 24px; text-align: left; margin-bottom: 25px'>Products</div>
<div style='font-style: oblique; font-size: 18px; text-align: right; margin-bottom: 25px'>
<form method='"+form.method+#"' action='"+form.action+#"'>
<input id='txtSearch' name='txtSearch'>
<input type='button' id='btbSearch' text='Search' onclick='this.parentNode.submit();'>
</form>
</div>
<table width='100%' border='1' cellpadding='0' cellspacing='0'>"+tableBody+#"
</table>
";
The fixed part code of html is not necessarily consist with StringBuffer. If you want to generate the html dynamically, consider to use LINQ.
What should be done yourself are in the comments of the code. Notice that the txtSearch is not only given an id, but also name.

Link button inside a Repeater control, how to change the background/foreground color of clicked item?

I would like to show list of days in week (dynamic, some time all days, sometime only 2-3)
and then user will click on day and refresh the same page.
Above functionality is achieved by below code.
<asp:Repeater ID="DayList" Runat="server">
<ItemTemplate>
<asp:LinkButton ID="lbDayList" Runat="server" CommandName='<%# DataBinder.Eval (Container.DataItem, "wkdayVal")%>'
OnCommand="lbDayList_click"
DataBinder.Eval(Container.DataItem, "wkday")%>
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
I want to show the clicked day in different color!! Please help in achieving this functionality!
Have you considered creating a styles.css page and using the CssClass="" attribute of your LinkButton?
In your styles.css file you would have something like the following:
.Visited
{
color: #fff;
background: inherit;
text-decoration: none;
}
Then your link button's css attribute would use something like
CssClass="visited"
You'll want to do this on the PreRender portion of your Repeater so set the Repeater's OnPreRender attribute to Repeater_OnPreRender. Then in your codebehind create a function like so
protected void Repeater_OnPreRender(object sender, EventArgs e)
{
//get the index of the selected item
//loop through your items colleciton until you find the item with the corresponding index
//find your link button
//set your link button's css attribute.
}
The reason you would perform this in the PreRender stage is because your repeater already has the data loaded into it and the HTML that is passed back to the web browser has not yet been created.
Hope this helps. GS

Categories