Invoke Javascript method from code-behind based on a condition. - c#

This is my javascript method in .aspx file. I want to invoke this method from code-behind based on a certain condition:
function confirmboxAndHideMessage() {
//HideMessage();
var response = confirm("are you sure?.");
if (response == true) {
document.getElementById("<%=chkValidated.ClientID%>").checked = true;
HideMessage();
}
else {
HideMessage();
return true;
}
}
The condition upon which I want to invoke is something like this:
if (obj.fkValidationStatusId.HasValue && obj.fkValidationStatusId.Value.Equals(1))
{
btnProceedAddNewRecords.Attributes.Add("OnClick", "javascript:return confirmboxAndHideMessage();");
}
else
{
btnProceedAddNewRecords.Attributes.Remove("OnClick");
}
This condition is being exercised in a method which is called in PageLoad event inside
if (!IsPostBack) { /* condition */ }
It is not working and my guess is that the way i am adding the method in button attribute is wrong. My request is that, kindly suggest a way I can invoke this javascript method from my code-behind based on the stated condition. If you think that my approach is flawed, Please do suggest Alternatives. Thanks.

use to set/unset OnClientClick
if (obj.fkValidationStatusId.HasValue && obj.fkValidationStatusId.Value.Equals(1))
{
btnProceedAddNewRecords.OnClientClick="return confirmboxAndHideMessage();";
}
else
{
btnProceedAddNewRecords.OnClientClick="retun false;";
}

Just add the following code where the condition is like
public void test()
{
String name = "test";
if (name == "test")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "hdrEmpty", "if(confirm('are you sure you want to continue?')==true){ Testfunction(); };", true); return;
}
}
I am sure it will work for you.

You should return true or false from the function. You probably want to return true for a positive response:
function confirmboxAndHideMessage() {
var response = confirm("are you sure?.");
if (response == true) {
document.getElementById("<%=chkValidated.ClientID%>").checked = true;
HideMessage();
return true;
} else {
HideMessage();
return false;
}
}
Use lowercase for the event name (as XHTML is picky about that), and remove javascript: from the code:
btnProceedAddNewRecords.Attributes.Add("onclick", "return confirmboxAndHideMessage();");
Put the code that sets the attribute outside the check for IsPostBack, otherwise it will not be updated when the condition changes.

Related

Calling method from Fragment inside another Fragment

I have a problem. I have 2 fragments with methods. Now I want to call a method from Fragment2.cs inside Fragment1.cs. Here is the method from Fragment2.cs:
public void UpdateActionBar(int CurrentFragmentNum)
{
if (CurrentFragmentNum == 1)
{
btnBack.Visibility = ViewStates.Invisible;
btnNext.Visibility = ViewStates.Invisible;
}
else
{
btnBack.Visibility = ViewStates.Visible;
btnNext.Visibility = ViewStates.Visible;
}
if (CurrentFragmentNum == 3)
{
btnNext.Text = "Finish";
}
else
{
btnNext.Text = "Next";
}
}
And in Fragment1.cs I need to call this method! How can I do that... I already know how to call a method from the MainActivity using this:
(Activity as MainActivity)?.Method();
But now I want the method from another fragment.
I have already tried something like this:
(Fragment as Fragment2)?.Method();
But that gives me the error:
'Fragment' is a type, which is not valid in the given context
Can someone help me?
Please make search before ask, the question is very popular
google search

Is there a way how to step out form method and return page with updated element?

I have couple of method in code behind on asp.net application. I would like to return messages to user in Label in case of something happen during execution and stop execution.
Code is just as sample what I'm trying to achieve.
I already tried:
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
Response.Redirect("to same page");
Example: (I don't want to execute unzipFile method. I would like to reload current page with updated label)
protected void btnUpload_Click(object sender, EventArgs e) {
uploadFile(Server.MapPath("~/") + filename);
unzipFile(string newFile);
}
protected void uploadFile(string newFile) {
if (newFile != null)
{
Label.Text="This is not valid file!"
//stop processing load file with updated label
}
if (newFile.ContentType != "application/x-zip-compressed") {
Label.Text="This is not valid file!"
//stop processing load file with updated label
}
}
Just don't redirect. The postback is already to the current page and should render the current page unless anything tells is not to. Consider a simple case:
protected void Page_Load(/.../)
{
// set some values on the page
}
protected void btnClick(/.../)
{
label1.Text = "This is a test";
}
With only that code in the button click handler, the current page will reload after clicking the button and the only visible change will be that text output.
Your case isn't really different. Set the labels and don't redirect. For example:
if (newFile != null)
{
Label.Text = "This is not valid file!";
}
else if (newFile.ContentType != "application/x-zip-compressed")
{
Label.Text = "This is not valid file!";
}
else
{
// process the file
Response.Redirect("SomewhereElse.aspx");
}
However you structure the logic, ultimately your goal is to not do any more processing once you have your error condition and just allow the event handler to complete and the page to re-render.
Note: I think you also meant == null, and you can simplify the conditions. Consider:
if (newFile == null || newFile.ContentType != "application/x-zip-compressed")
{
Label.Text = "This is not valid file!";
}
else
{
// process the file
Response.Redirect("SomewhereElse.aspx");
}
If you don't want the else, you can accomplish the same with a return:
if (newFile == null || newFile.ContentType != "application/x-zip-compressed")
{
Label.Text = "This is not valid file!";
return;
}
// process the file
Response.Redirect("SomewhereElse.aspx");

Is it possible to invoke functions used to create parameters for a method from inside that method? (C#)

This is a bit hard to explain, but I'm hoping this example will clear it up.
Say I have some function call Visible:
public bool Visible(/* Some page element */)
{
// Checks if something on a webpage is visible. Returns a "true" is yes, and "false" if not
}
Is it possible to some how wait for this function to return true? What I've written out so far looks like this:
public void WaitUntil(/*function returning bool*/ isTrue)
{
for (int second = 0; ; second++)
{
if (second >= 12)
{
/* Thow exception */
}
else
{
if (isTrue /*calls the isTrue function with given parameters*/)
{
return;
}
}
}
}
Such that these two method could be used together like:
WaitUntil(Visible(/* Some page element */));
to wait until a page element is visible... Is this possible?
Here is how to do it (although you should consider using events as this kind of "waiting" is strongly discouraged)
/*Important Note: This is ugly, error prone
and causes eye itchiness to veteran programmers*/
public void WaitUntil(Func<bool> func)
{
DateTime start = DateTime.Now;
while(DateTime.Now - start < TimeSpan.FromSeconds(12))
{
if (func())
{
return;
}
Thread.Sleep(100);
}
/* Thow exception */
}
//Call
WaitUntil(() => Visible(/* Some page element*/));

Find failed validators asp.net

I have a page, where I want to log every validation message which the user failed to meet the requirements the associated field.
The problem is my postback/button click never occurs (maybe because of clientside validation), and therefore the logging never takes place before the user actually got every field right (no validation errors).
The button click event method:
protected void btnNext_Click(object sender, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
//code
}
else
{
foreach (IValidator validator in Validators)
{
if (!validator.IsValid)
{
PageValidatorErrors error = new PageValidatorErrors
{
WebsiteID = AppState.WebsiteID,
Page = Request.Url.AbsolutePath,
URL = Request.Url.ToString(),
UserIP = Tools.GetIP(),
ErrorMessage = validator.ErrorMessage,
CreatedDate = DateTime.Now
};
pageValidatorErrorsRep.insert(error);
}
}
}
}
Any ideas, how I could log theese messages?
Edit:
<script type="text/javascript">
function validatePage()
{
if (window.Page_IsValid != true)
{
//Page_Validators is an array of validation controls in the page.
if (window.Page_Validators != undefined && window.Page_Validators != null)
{
//Looping through the whole validation collection.
for (var i = 0; i < window.Page_Validators.length; i++)
{
window.ValidatorEnable(window.Page_Validators[i]);
//if condition to check whether the validation was successfull or not.
if (!window.Page_Validators[i].isvalid)
{
var errMsg = window.Page_Validators[i].getAttribute('ErrorMessage');
alert(errMsg);
}
}
}
}
}
</script>
Here is part of the solution, you can get the validates/true false by invoking it client side:
http://razeeb.wordpress.com/2009/01/11/calling-aspnet-validators-from-javascript/
function performCheck()
{
if(Page_ClientValidate())
{
//Do something to log true/ false
}
}
Try to change EnableClientScript property on all validators to false. All your validations will occur only on server side.

If condition's logic is not working

I have added one label in form that is not visible to user.Base on the text that label contain proceed further.
Here is my logic,but it fail.I wanted like this,if label contain "No match" or "Time out",should not proceed.
If((!label.Text.Contain("No match")) || label.Text.Contain("Time out"))
{
// proceed further code
}
else
{
// code
}
Here Label contain "No match",then it move to else part that is right.But when label contain "Time out",then it go inside the if loop.So I modified code like this
If((!label.Text.Contain("No match")) || (!label.Text.Contain("Time out")))
{
// proceed further code
}
else
{
// code
}
still not working.If label contain "Time out",still it go into if loop not else loop.Label contain only one text at a time either "No match" or "Time out" or any other text.
I suspect you want:
if(!(label.Text.Contains("No match") || label.Text.Contains("Time out")))
{
// proceed further code
}
else
{
// code
}
Note the bracketing. The inner part is
label.Text.Contains("No match") || label.Text.Contains("Time out")
and then that's inverted. I would probably pull that out into a separate variable:
bool timedOutOrNoMatch = label.Text.Contains("No match") ||
label.Text.Contains("Time out");
if (!timedOutOrNoMatch)
{
}
else
{
}
Alternatively, invert the sense of it:
if (label.Text.Contains("No match") || label.Text.Contains("Time out"))
{
// Do whatever was in your else block.
}
else
{
// Do whatever was in your first block.
}
If your response to the "bad" labels is something that lets you return or throw an exception, this can also reduce the amount of nesting:
if (label.Text.Contains("No match") || label.Text.Contains("Time out"))
{
output.Text = "Go away";
return;
}
// Now handle the success case
Try with following code:
if(!(label.Text.Contains("No match") || label.Text.Contains("Time out")))
{
// proceed further code
}
else
{
// code
}
If you want to get right with your modified code, use AND operator:
if(!label.Text.Contains("No match") && !label.Text.Contains("Time out"))
{
// proceed further code
}
else
{
// code
}
To write your code in more understood form , you should write it in a way that it is readable and more understandable. I prefer to write this statement like this
bool ProceedFurther()
{
//Don't proceed if No Match
if(!label.Text.Contains("No match")) return false;
//Don't proceed if Time out
if(!label.Text.Contains("Time out")) return false;
//Proceed otherwise
return true;
}
and call ProceedFurther method at desired location.
If you really want only that statement, following is the best (mostly people forget to change || to && after they change the condition to negative (using !).
if(!label.Text.Contains("No match") && !label.Text.Contains("Time out"))

Categories

Resources