Can I create a custom attribute that runs a codebehind method? - c#

I added an onkeyup attribute on Page_Load for a TextBox. I have it so that it is able to run a JavaScript function fine. I was wondering if I can change it to run a method in the code-behind file. I tried this.methodname, but it asks for a string as a parameter.
The TextBox in question:
<asp:TextBox ID="txtCurrBlk" runat="server" onkeyup="txtUpdate()"
style="width:80px" Text='<%#Eval("currentBlack") %>'
AutoPostBack="true" />
Under page_load in this C# file:
txtCurrBlkTotal.Attributes.Add("onKeyUp", "CallScript(this)");
The function I want to run in the same code behind file:
protected void keypressUpdateTotals()
{
readingTextChanged();
updateTotals();
}
So the onkeyup will currently run whatever JavaScript function I set it to, but I need it to run a method inside the code-behind instead.

The TextBox control only has the server-side TextChanged event, and you cannot easily make a "custom" server-side event. However, you can let your JavaScript CallScript() function make a post-back to the server by calling the _postback() function.
Add the OnTextChanged attribute to your TextBox control (I recommend removing the AutoPostBack attribute too, but that's up to you):
<asp:TextBox ID="txtCurrBlkTotal" runat="server"
onkeyup="CallScript(this)"
OnTextChanged="txtCurrBlk_TextChanged" />
I've added the onkeyup directly here, but you can use txtCurrBlkTotal.Attributes.Add("onKeyUp", "CallScript(this)");, if you want.
Now, at the end of the CallScript() function, call the _postback() function for your TextBox control:
function CallScript(sender) {
//...
__doPostBack("<%= txtCurrBlkTotal.ClientID %>", "");
}
This will post-back to the server every time the onKeyUp event is fired. You can capture and process that in the TextChanged event:
protected void txtCurrBlkTotal_TextChanged(object sender, EventArgs e) {
keypressUpdateTotals();
}
Alternatively, you can make your JavaScript CallScript() function make an Ajax call to your code-behind keypressUpdateTotals() function. I think that's a better solution, but you can decide for yourself.

Related

how to call a javascript function from codebehind in asp.net

protected void addSchoolButtonClick(object sender, ImageClickEventArgs e)
{
Page.ClientScript.RegisterStartupScript(GetType(), "MyKey1", "SchoolSearchPopUp();", true);
/*Some code*/
}
I am developing a website in asp.net.At a Hyperlink onclick event i want to call a javascript function"SchoolSearchPopUp()".this function is for creating a new popup window and it is working correctly.But my problem is ,a javascript function is calling or pop window opens only after executing the rest of the code in that function and that code need's some data that occurs as a result of popup.How can i create the popup before executing the rest of code in that function.
Change your postback trigger to something within the popup.
I don't think javascript can be called from code behind. C# is running from the server and java is all client side. There's a good explanation to a similar question here: http://forums.asp.net/t/1117189.aspx
If you need to execute a javascript function, you could try changing the hyperlink to a button and making use of the OnClientClick property. This executes script client side rather than calling a method on the server.
<asp:button id="Button1"
text="Click Here"
onclientclick="SchoolSearchPopUp()"
runat="server" />
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
You will need to write JavaScript on the page to handle the click of the button first and then call to the page method on the server.
Add an OnClientClick attribute to your button element and run your JavaScript method from there:
<asp:Button ID="TestButton" OnClientClick="SchoolSearchPopup()" Text="Click Me" OnClick="addSchoolButtonClick" runat="server"/>
<script type="text/javascript">
function SchoolSearchPopup()
{
alert("Popup");
}
</script>
If you want to execute some javascript before your postback you will need to register your hyperlink's click event to a js method, then submit your post to the server after performing whatever client side logic you are looking to run. (not the other way around, using RegisterStartupScript)
Example:
$("#myHyperLink").click(function() {
// do page logic, in your case show a modal window
$("#myModalDivContainer").show();
// submit your post to the server... replace targetClientID with ID of server control you're posting to
__doPostBack('targetClientID', '');
// NOTE: If you want to perform an AJAX request instead simply use some jQuery here instead. it's up to you how to handle the request from this point :)
});
Hope this helps!

CustomValidator ServerValidate method does not fire

I've put a CustomValidator on my form. I have not set its ControlToValidate property. In its ServerValidate event I've written the following:
protected void CustomValidator1_ServerValidate(object source,
ServerValidateEventArgs args)
{
args.IsValid = false;
}
I put a breakpoint to this method but it seems to never come to that point. But if I do this on another form it works like a charm.
The ValidationGroup property of both the button and the CustomValidator are the same
I tried deleting this property in both the button and the CustomValidator, still does not work.
It seems as there's something formwide. I just put a CustomValidator on the form and do not touch any of its properties other than just setting its ServerValidate event method.
EDIT: Here's the aspx part:
<asp:CustomValidator ID="CustomValidator2" runat="server"
ErrorMessage="This is a test"
onservervalidate="CustomValidator1_ServerValidate"
ValidationGroup="PA"></asp:CustomValidator>
<asp:Button ID="btnPensionersOK" runat="server" Text="OK" Width="75px"
onclick="Button1_Click" ValidationGroup="PA" />
Try to force the validation in the button-click handler via Page.Validate:
protected void Button1_Click(Object sender, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
// servervalidate should have been called
}
}
Edit(from comments):
If you want the customvalidator to validate if nothing was entered/selected in your controls, you need to set ValidateEmptyText to true. You also might want to let the CustomValidator replace the RequiredFieldValidators.
I assume that the validator-order on the aspx decides whether or not a customvalidator's severvalidate is called if a previous Validator already has made Page.IsValid=false. Or ASP.NET is so smart that it assumes the SeverValidate to be costlier than a simple text-is-empty check.
I would also like to put some more help for those who will use CustomValidators and RequiredFieldValidators at the same time. One should take into account that Client side validation takes place first. And the server side validation will occur only after PostBack. I'm sure you got it but just in case this is not quite clear: It means first all the controls that are bound to certain client side working validators must be valid to let Postback to occur. After Page. IsValid is True server side stuff takes place and posts back any changes which includes server side validation messages.
So here are the ways one can make both CustomVCalidators and other built in validators to work at the same time.:
Set both groups of validators to work on Client side. In this case we must ensure that for the custom valitor(s) we spacify the script that will make validation on the client side. Without writing script and just filling in the ServerValidate method the validation will take place in the server.Even if EnableClientScript property is set to True.
Set both groups of validators to work on server side. To do so simply set EnableClientScript to False. But note that this will load the server.

onkeyup event asp.net

Hi how can i register and call a server side event for onkeyup event in asp.net textbox.
Is it possible?
thank you
TextBox Web control doesn't provide onkeyXXX events instead subscribe to OnTextChanged event;
<asp:TextBox ID='Textbox1' runat='server' OnTextChanged='HandleTextbox1OnTextChanged'>
</asp:TextBox>
public void HandleTextbox1OnTextChanged(Object sender, EventArgs e)
{
}
But you can provide onkeyXXX behavior from client-side.
You can add client-side handler like :
Textbox1.Attributes.Add("onkeyup", String.Format("onKeyUp({0})", TextBox1.ID));
And in the page
`<script language='javascript' type='text/javascript'>
function onKeyUp(id) { //do something; }
</script>`
Also you could use PageMethods to make a call to server-side web methods (static methods) from javascript functions.
This link might help.

Passing parameters into a ASP.Net Button control when clicked

I have an asp button (the code is below). I have the event handler working, but I want to pass a string (which is the result of a javascript function) into the event handler function. Is there a way to do that?
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" Text="Run" />
Normally the way you would do this is to have you javascript modify an input control so that the value will be posted back with the Button click. If you want the user to visually not be able see the data that your javascript is modifying to post back then you can write it to a HiddenField.
You can use the OnClientClick to setup the javascript to run before the postback happens to ensure your modified value is put into the input control. Eg:
<asp:Button ID="yourButton" runat="server" Text="Click Me!"
OnClientClick="YourFunctionToAddStringToControl(); return true;"
OnClick="yourButton_Click" />
So you just need to swap the call to YourFunctionToAddStringToControl with your modified javascript function that is writing the value to a HiddenField or another input control. Then update your server side click handler to access the field.
Side Note: When using javascript to write to server side controls such as HiddenField, don't forget to use <%= yourHiddenField.ClientID %> to get the correct control name.
Not in the way you're asking.. However...
You CAN add an ASP:HiddenField, and use Javascript to modify the value of the HiddenField to be your string. Then you can access this in your Button Click event.
An example can be found here.

Postback events from within DataView

I'm presenting information from a DataTable on my page and would like to add some sorting functionality which goes a bit beyond a straight forward column sort. As such I have been trying to place LinkButtons in the HeaderItems of my GridView which post-back to functions that change session information before reloading the page.
Clicking my links DOES cause a post-back but they don't seem to generate any OnClick events as my OnClick functions don't get executed. I have AutoEventWireup set to true and if I move the links out of the GridView they work fine.
I've got around the problem by creating regular anchors, appending queries to their hrefs and checking for them at page load but I'd prefer C# to be doing the grunt work. Any ideas?
Update: To clarify the IDs of the controls match their OnClick function names.
You're on the right track but try working with the Command Name/Argument of the LinkButton. Try something like this:
In the HeaderTemplate of the the TemplateField, add a LinkButton and set the CommandName and CommandArgument
<HeaderTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="sort" CommandArgument="Products" Text="<%# Bind('ProductName")' />
</HeaderTemplate>
Next, set the RowCommand event of the GridView
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "sort")
{
//Now sort by e.CommandArgument
}
}
This way, you have a lot of control of your LinkButtons and you don't need to do much work to keep track of them.
Two things to keep in mind when using events on dynamically generated controls in ASP.Net:
Firstly, the controls should ideally be created in the Page.Init event handler. This is to ensure that the controls have already been created before the event handling code is ran.
Secondly, you must assign the same value to the controls ID property, so that the event handler code knows that that was the control that should handle the event.
You can specify the method to call when the link is clicked.
<HeaderTemplate>
<asp:LinkButton
ID="lnkHdr1"
Text="Hdr1"
OnCommand="lnkHdr1_OnCommand"
CommandArgument="Hdr1"
runat="server"></asp:LinkButton>
</HeaderTemplate>
The code-behind:
protected void lnkHdr1_OnCommand(object sender, CommandEventArgs e)
{
// e.CommandArgument
}

Categories