Check which server side method is being called - asp.net

How to know which server side method is called on button click. I am new and everything in the code is wrapped. So on
<asp:Button ID="Apply" runat="server onClick = "Apply_Click" .. >
And on the Button click function it just has>>
Apply_Click(object sender, EventArgs e)
{
GetXML();
}
the GetXML method just generates the XML file.
But in click it actually validates the coupon entered and if it is correct than allows next page, else displays error. The GetXML() just prepares a XML file, it has no Stored Procedure call or any other method which may make this call of Validating the Coupon.
Can anyone tell me how to see which server side method is being called to validate the Coupon.
If it is a custom method than how to see its code.

If you don't want to execute validation with Apply_Click specify it:
<asp:Button ID="Apply" CausesValidation="false" runat="server
onClick = "Apply_Click" .. >
As for validation method, it can be any custom validator
<asp:CustomValidator OnServerValidate="magic_here" />
or custom javascript or Page_Load or Page_Init piece of code.

Related

calling server side c# from <input> element in repeater

<td><input type="image" style="border-width:0" alt="Do an Edit" title="Edit the repeater row" tabindex="0" src='<%=ResolveUrl("~/css/image.png") %>' onclick='showModal(<%#Container.ItemIndex %>); return false;'/></td>
I am already using onClick() for invoking a javascript method. Now, I want to add another an event to this element to trigger a server side event- say using onKeyUp- and pass 1 parameter on the repeater to the server side.
Is this possible or I have to first call javaScript and then Javascript on the page will callinto my server side. (I think this way the method in the server side code has to be static).
You can add an invisible LinkButton to your page (for example LinkButton with a blank text) and from your client-side onKeyUp event call LinkButton's click() method and catch Click event server side.
To pass parameter you can use any control that is readable both client-side and server side, for example hidden field.
For example - your HTML markup can look something like this:
<asp:TextBox ID="xtxtMyText" runat="server" onkeyup="doMyPostback()"></asp:TextBox>
<asp:HiddenField ID="xhidParam" runat="server" />
<asp:LinkButton ID="xlnkMyPostBack" runat="server" OnClick="xlnkMyPostBack_Click"></asp:LinkButton>
<script type="text/javascript">
function doMyPostback(e) {
var evt = window.event ? window.event : e;
if (evt.keyCode == 13) {
document.getElementById('xhidParam').value = document.getElementById('xtxtMyText').value;
document.getElementById('xlnkMyPostBack').click()
}
}
</script>
Here you have a textbox that triggers keyUp event, hidden linkbutton that causes server-side Click event and hidden field that is used to pass parameter. In this scenario if user hits Enter, content of textbox is copied to the hidden variable and the linkbutton is clicked.
On the server side you can handle that event and read the passed parameter from the hidden field, e.g.
protected void xlnkMyPostBack_Click(object sender, System.EventArgs e)
{
Response.Write(xhidParam.Value);
}

Using of MessageBox class in Asp.Net

I am using MessageBox class in Asp.NET with C# by imposing the namespace
using System.Windows.Forms
I have the following code:
/* Method for displaying the Message Box */
public void MsgBox()
{
string message = "Do you want to modify the rate list?";
string caption = "";
MessageBoxButtons buttons = MessageBoxButtons.YesNoCancel;
DialogResult result;
result = MessageBox.Show(message, caption, buttons);
if (result == DialogResult.Yes) {
Response.Redirect("PaperRateList.aspx");
}
}
/*Calling of the above method in the following event */
protected void Save_Click(object sender, EventArgs e)
{
CompanyMaster_Insert();
RateList_Save();
MsgBox(); /*method*/
}
Now the problem is that the message box is appearing behind the form in minimized mode.and the form can be closed before closing the message bos.I want this messagebox on the form and i want to close the form after closing the message box.
MessageBox in web environment is not the best path to go, as it's a cheap way of implementing a windows form feature.
You have 2 ways to do this, server side (if you need to process some data) or client side (if you have all the data in the page and you can process it using javascript).
For you particulary example, you probably have a submit button like:
<asp:Button id="btnSave" runat="server"
onclick="btnSave_Click" text="Save Form" />
try to add this:
onclientclick="return confirm('Do you want to modify the rate list?');"
so it ends up like:
<asp:Button id="btnSave" runat="server"
onclick="btnSave_Click" text="Save Form"
onclientclick="return confirm('Do you want to modify the rate list?');" />
That's just using a javascript method called confirm.
To make nice MessageBox examples, and to avoid the user not to mess up with the page while the message is visible, it's called Modal Dialog or Modal Window, try to search for it...
jQuery UI has a Modal element that you can use, and if you fancy AJax stuff and you're a beginner in ASP.NET, I strongly suggest you to try the ASP.NET Control Toolkit
try
WebMsgBox class represents a message box for ASP.NET applications. This class has a static method Show, which is used to display a message box. The Show method takes a single argument of string type, which is the message you want to display.
private void Page_Load( object sender, System.EventArgs e )
{
MessageBox.Show( "Hello World!" );
MessageBox.Show( "This is my second message." );
MessageBox.Show( "Alerts couldnt be simpler." );
}
You can use ModalPopupExtender of AJAXControlToolkit:
ModalPopup Example

How can i turn off ASP.NET required field validator "lost focus" behaviour

I have some code where I need two separate required field validators for one control, both in separate validation groups which are then validated by two separate buttons.
This approach works well when the buttons are clicked but both validators show if I enter a value in the textbox and then remove it.
Is there a way to turn this"lost focus" validation off? I only need it to validate when the buttons are clicked.
EDIT
Unfortunately, if I set EnableClientScript=false then I dont have any client notifications. What I want is for the dynamic error message to show (effectivly in the OnClientClick event of the button) but not the "lost focus" of the textbox.
Is there some way I can disable or "unhook" the lostfocus client event?
EDIT
A combination dDejan's answer and womp's answeer here sorted the problem perfectly.
My final code looks like this (for anyone else with a similar situation)...
Javascript...
<script type="text/javascript">
$(document).ready(function() {
$('body').fadeIn(500);
//Turn off all validation = its switched on dynamically
$.each(Page_Validators, function(index, validator) {
ValidatorEnable(validator, false);
});
});
function ToggleValidators(GroupName) {
$.each(Page_Validators, function(index, validator) {
if (validator.validationGroup == GroupName) {
ValidatorEnable(validator, true);
} else {
ValidatorEnable(validator, false);
}
});
}
</script>
ASPX Control Example...
<telerik:RadTextBox Width="196px" ID="txtFirstName" runat="server" MaxLength="50" Skin="Black"></telerik:RadTextBox>
<asp:RequiredFieldValidator ID="valFirstName" CssClass="Validator" runat="server" EnableClientScript="true" Display="Dynamic" ErrorMessage="You must enter your first name." ControlToValidate="txtFirstName" ValidationGroup="NeededForEmail"></asp:RequiredFieldValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" CssClass="Validator" runat="server" EnableClientScript="true" Display="Dynamic" ErrorMessage="You must enter your first name." ControlToValidate="txtFirstName" ValidationGroup="NeededForSubmit"></asp:RequiredFieldValidator>
ASPX Button Code...
<asp:Button ID="btnGetConfCode" runat="server" Text="Get Confirmation Code" OnClientClick="ToggleValidators('NeededForEmail')" OnClick="btnGetConfCode_Click" Width="100%" ValidationGroup="NeededForEmail"/>
<asp:Button ID="btnRegisterUser" runat="server" Text="Register" OnClientClick="ToggleValidators('NeededForSubmit')" OnClick="btnRegisterUser_Click" Width="100px" ValidationGroup="NeededForSubmit" />
So, now there is no validation until a user clicks either the "Get Email Confirmation Code" button or the "Register" button.
If they click the "Get Email Confirmation Code" button all of the controls validate apart from the textbox where the user is to input the email validation code and we only see one validator message.
If they click the "Register" Button then all of the controls validate and we only see one validation message.
If either button is pressed, the user goes back, adds and then removes some text then we only see one validator. Before this change you used to see both messages saying the same thing.
Thank you for help guys
You can set if the validators are "active" or not with client side code using the ValidatorEnable function. Basically it goes like this
var validator = document.getElementById('<%=Validator1.ClientID%>');
ValidatorEnable(validator , state); //where state is boolean
You can also trigger the validator to validate on some event (like for example the click of the buttons) using the ValidatorValidate(validator) function.
I am not sure which would work better for you (enabling/disabling the validators or custom triggering of the validation) but I suggest this article that will guide you in the right direction
ASP.NET Validation in Depth
There's no way to unhook them if EnableClientScript=true.
What you could do is set it to false. Then create a javascript validation method that is called on your submit-button onClientClick event.
In your method, you would have to call ValidatorValidate(control) for each control you want to validate client side
There's an example here:
http://msdn.microsoft.com/en-us/library/Aa479045#aspplusvalid_clientside
You could turn off the javascript validation by setting EnableClientScript="false" that would get rid of the lost focus validation.
You can use Custom Validator controls instead and either validate the input using Javascript on the client or within the event handler on the server. Ensure you set ValidateEmptyText="true" on the validation controls otherwise the events will not fire on an empty field.
Try to Enable on Both button click using javascript and disable it on textbox blur event.
Try resetting the onchange event for the input-control.
$(document).ready(function () {
$("#controlid").each(function () { this.onchange = null; })
});
var validator = document.getElementById('<%=Validator1.ClientID%>');
ValidatorEnable(validator , state);
It is working in javascript but when we use the page.Isvalid function on Server side it creates the problem to check page is valid or not.
simply type this code in page_load event
textboxname.Attributes.Add("onblur","ValidatorOnChange(event);");

show modal pop and redirect

I have a link on the page and i want when the user is pressing it, to evaluate a method where i check if the usser is logged in. If not, i want to show up a modal popup.
I know how to do the back-end checking and how to redirect the user but i have problems
with the link button:
<asp:LinkButton ID="LinkButton1" runat="server"
OnClientClick="redirectToWishList()">LinkButton</asp:LinkButton>
When i press it, it does a full postback instead evaluating the method where i show up the modal pop.
Do you have any workaround to not fire a full postback but check the method where i am doing the redirect?
Ps: The method which has to fire:
public void redirectToWishList(object sender, EventArgs e)
{
ASP.usercontrols_loginpopup_ascx loginUserControl = (ASP.usercontrols_loginpopup_ascx)UtilsStatic.FindControlRecursive(Page, "loginPopUp");
ModalPopupExtender modal = (ModalPopupExtender)loginUserControl.FindControl("loginPopUp");
modal.Show();
}
You need to call redirectToWishList as a function (including the parens): redirectToWishList()
<asp:LinkButton ID="LinkButton1" runat="server"
OnClientClick="redirectToWishList();return false;">LinkButton</asp:LinkButton>
Also, if you return false in your function, you do not need to in the tag.
UPDATE
I misunderstood. The OnClientClick is for invoking JavaScript, not running methods in your code-behind. You need to OnClick instead.
Do you return false from your redirectToWishList function?
You shouldn't need the return false in the LinkButton declaration.

ASP.NET Page Validation

Related Article
On a similar topic to the above article, but of a more specific note. How exactly do you handle items that are in the viewstate (so they are included on submit), but can also be changed via AJAX. For instance, say we had a dropdown list that was populated through an AJAX web service call (not an update panel). How can I get the page to validate once the dropdownlist's items have been changed?
You're not validating the dropdown list are you? You're validating the value a user selected. It's pretty much the same advice as the other post, since javascript or other tools can alter the html or create their own POST's, you must always validate on the server side. Assume all client requests can be tampered with, and assume that no client-side validation has occurred.
If you're using the web forms model ....
If you just want to check a value was selected in the dropdown myAjaxDropDown, use the
<asp:RequiredFieldValidator id="dropdownRequiredFieldValidator"
ControlToValidate="myAjaxDropDown"
Display="Static"
InitialValue="" runat=server>
*
</asp:RequiredFieldValidator>
You could also want to look at the asp:CustomValidator - for server side validation:
<asp:CustomValidator ID="myCustomValidator" runat="server"
onservervalidate="myCustomValidator_ServerValidate"
ErrorMessage="Bad Value" />
Both plug into the validation framework of asp.net. e.g. when you click a button called SumbitButton
protected void myCustomValidator_ServerValidate(object source, ServerValidateEventArgs e)
{
// determine validity for this custom validator
e.IsValid = DropdownValueInRange(myAjaxDropDown.SelectedItem.Value);
}
protected void SubmitButton_Click( object source, EventArgs e )
{
Validate();
if( !IsValid )
return;
// validators pass. Continue processing.
}
Some links for further reading:
ASP.Net 2.0 Quickstart - Validating Form Input Controls
ASP.NET Validation Controls – Important Points, Tips and Tricks
You can call the Page_Validate() function from your javascript code, it will trigger the asp.net validators on the page, it is basically similar to Page.Validate() in server code
why not validating onChange even in the dropdownlist?
just add the script manager and add that property to the onchange in the Page_Load event
' Creating the javascript function to validate
Dim js As String
js = "function validateDDL1(ddl) { alert(ddl.value); }"
' Adding onChange javascript method
DropDownList1.Attributes.Add("onchange", "validateDDL1(this);")
' Registering the javascript
ScriptManager.RegisterClientScriptBlock(Me, GetType(String), "validateDDL1(ddl)", js, True)

Resources