Updating ValidatorCallOut Error Message from Javascript - asp.net

I am trying to update the error message for a CustomValidator that uses a ValidatorCallOut via javascript. Basically its checking to see if a number entered is an increment of a specified number. I have some code that will update the error message the first time it is run, but after that it will no longer update the error message, although through javascript alerts I see the values are actually being updated. Here is the client side javascript validation function I'm using:
function checkIncrement(sender, args) {
var incrementValue = parseInt(sender.orderIncrement); // Custom attribute registered with RegisterExpandoAttribute
var remainder = args.Value % incrementValue;
if ((remainder) != 0) {
var remainder, lowRange, highRange;
lowRange = parseInt(args.Value - remainder);
highRange = parseInt(lowRange + incrementValue);
sender.errormessage = "Closest possible values are <b>" + lowRange + "</b> or <b>" + highRange + "</b>"; // Gets updated once, but not after that
alert("Low Range: " + lowRange); // always updated with current value
args.IsValid = false;
return;
}
args.IsValid = true;
}
Any idea on how to keep the error message updated every time this is run to validate?

Try the following:
sender.errormessage = "Your message here";
var cell = sender.ValidatorCalloutBehavior._errorMessageCell;
// cell is going to be null first time.
if (cell != null) {
cell.innerHTML = "Your message here";
}
The reason why the message sticks once it has been initialized is because Callout is not created initially. Once it has been created, Callout is just hidden and is not recreated on subsequent showing. Thus, message that it was initialized with when it was created will stick and persist. The above code is a hack and there really should be a method along the lines of set_ErrorMessage, but there isn't one.

Related

nextPage() method - not functioning

I have a datasource that contains > 1000 records. The current Query page size is at 100.
I have a need to loop through each item, and try to find a record that matches input given by the user. Fairly simple use-case, however, I can't seem to get the script to loop through the pages so it just finishes its loop at the query page size of 100 and therefore only searching the first 100 records.
I've tried putting in
app.datasources.Vehicles.nextPage();
at the end of the for loop and then call regoExists again with the new page but it doesn't work. How is nextPage() meant to be used in client scripts?
function regoExists(rego){
var regoUp = rego.toUpperCase();
regoUp = regoUp.trim();
ds = app.datasources.Vehicles.items;
for (var i in ds){
if (ds[i].registration === regoUp){
console.log(ds[i].registration + " equals " + regoUp);
app.datasources.Vehicles.query.filters.registration._equals = regoUp;
return true;
} else {
console.log(ds[i].registration + " does not equals " + regoUp);
continue;
}
}
}
Rather than looping through each record and performing the query on each individual record I would suggest introducing a textbox widget in the same datasource and setting the binding to:
#datasource.query.filters.registration._equals
Then load the datasource via a button click or via the onValueEdit event of the textbox widget. If the registration value exists, it will be returned in a table presumably, and if it doesn't exist no records would be returned.

Stop execution of a page

I have a task board, some person is working on some task, if task is assigned to another person by his manager the first person who is working on the task board, his execution should be stopped, and a message should be displayed that "This task is assigned to some one else."
I tried using following in page load.
//Code Behind
if (!Owner)
{
SomecontrolsToHide();
MessageDisplay(); // JavaScript function call using RegisterStartupScript()
Response.End();
}
protected void MessageDisplay()
{
string dbMessage = "Task is assigned to someone else.";
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(typeof(Page), "ShowMessageWrapup_" + UniqueID, "showMessageDisplay('','" + dbMessage + "');", true);
}
// JavaScript function that displays message.
function showMessageDisplay(args, displayMessage) {
if (displayMessage != "") {
document.getElementById("spanMessage").innerHTML = displayMessage;
document.getElementById("spanMessage").style.display = 'inline';
}
}
It stops the execution but message is not displayed and Controls are not hidden too.
What should I do?
Don't do Response.End(). Just return without doing anything.
This will show the message box. Try this.
Response.Write(#"<script language='javascript'>alert('You are not allowed for this task !!!')</script>");

Object reference not set to an instance of an object error

I have Default.aspx and Upload.aspx.
I'm passing Id through query string to default.aspx(like:http://localhost:3081/default.aspx?Id=1752).In default page i have a link button to open the upload.aspx to upload file.When i use the Request.QueryString["Id"] in upload.aspx,it is showiing error as "Object reference not set to an instance of an object".I'm dealing with RadControls.
To open when i click a link(OnClientClick="return ShowAddFeedBackForm()") i have code like:
<script>
function ShowAddFeedBackForm() {
window.radopen("Upload.aspx", "UserListDialog");
return false;
}
</script>
I'm using detailsview in upload page with a textbox and a fileupload control.
code to bind when a file upload in upload.aspx
protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
string qString = Request.QueryString["Id"].ToString();
if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
{
//string qString = Request.QueryString["Id"].ToString();
//int Projectid = Convert.ToInt32(Session["ProjectId"]);
ProTrakEntities objEntity = new ProTrakEntities();
TextBox txtTitle = DetailsView1.FindControl("txtTask") as TextBox;
//RadComboBox cmbStatus = DetailsView1.FindControl("cmbStatus") as RadComboBox;
//var id = (from project in objEntity.Projects where project.ProjectId == Projectid select project).First();
RadComboBox cmbTaskType = DetailsView1.FindControl("cmbTasktype") as RadComboBox;
//RadComboBox cmbTaskPriorty = DetailsView1.FindControl("cmbPriority") as RadComboBox;
string Description = (DetailsView1.FindControl("RadEditor1") as RadEditor).Content;
var guid = (from g in objEntity.Projects where g.ProjectGuid == qString select g).First();
int pID = Convert.ToInt32(guid.ProjectId);
ProjectFeedback objResource = new ProjectFeedback();
objResource.ProjectId = pID;
objResource.Subject = txtTitle.Text;
objResource.Body = Description;
objResource.CreatedDate = Convert.ToDateTime(System.DateTime.Now.ToShortDateString());
objResource.FeedbackType = cmbTaskType.SelectedItem.Text;
objEntity.AddToProjectFeedbacks(objResource);
objEntity.SaveChanges();
DetailsView1.ChangeMode(DetailsViewMode.ReadOnly);
ClientScript.RegisterStartupScript(Page.GetType(), "mykey", "CloseAndRebind('navigateToInserted');", true);
}
}
Getting error at querystring statement-"Object reference not set to an instance of an object"
The query string is not inherited when you open a new page. You have to include the id in the URL, i.e. Upload.aspx?id=1752.
Edit:
A simple solution would be to just copy the search part of the page URL:
window.radopen("Upload.aspx" + document.location.search, "UserListDialog");
However, typically you would use the id value that you picked up from the query string in the server side code and generate client code to use it.
I am not sure but if I had to guess I would question whether the window object has been instantiated at the time you call radopen in the script section of your page. You should put a msgbox before the call window.radopen() call to print the contents of the window object if it is null that is your problem otherwise this will take more digging. Just my two cents.
I also noted that if the guid query returns no results the call to .First() will cause this error as well. Just another place to check while researching the issue.
There is one last place I see that could also throw this error if the objEntities failed to construct and returned a null reference then any call to the properties of the object will generate this error (i.e objEntitiey.Projects):
ProTrakEntities objEntity = new ProTrakEntities();
var guid = (from g in objEntity.Projects where g.ProjectGuid == qString select g).First();
This error is occurring because, as the other answerer said, you need to pass the ID to the RadWindow since the RadWindow doesn't know anything about the page that called it. You're getting a null reference exception because the window can't find the query string, so it's throwing an exception when you try to reference .ToString().
To get it to work, make your Javascript function like this:
function ShowAddFeedBackForm(Id) {
window.radopen(String.format("Upload.aspx?Id={0}", Id), "UserListDialog");
return false;
}
In the codebehind Page_Load event of your base page (ie, the page that is opening the window), put this:
if (!IsPostBack)
Button.OnClientClick = string.Format("javascript:return ShowAddFeedBackForm({0});", Request.QueryString["Id"]);
Of course, Button should be the ID of the button as it is on your page.

setInterval works when alert is included in if conditions, else it works only once

this question might be seems to be the similar question asked previously but its not.
My question is following :
I have code snippet as follows :
var i = 0;
function func2() {
if (i==0){
document.getElementById('frame1').contentWindow.opts[selected].setAttribute('name','channels');
var strValue = document.getElementById('frame1').contentWindow.opts[selected].getAttribute('name');
//alert("Attribute value set :" + strValue);
document.getElementById('frame1').contentWindow.handleKeyCode(VK_ENTER);
i++;
}
else if(i==1){
// For Channels section -- "Get current channel details"
document.getElementById('frame1').contentWindow.opts[selected].setAttribute('name','get');
var strValue = document.getElementById('frame1').contentWindow.opts[selected].getAttribute('name');
//alert("Attribute value set :" + strValue);
document.getElementById('frame1').contentWindow.handleKeyCode(VK_ENTER);
i++;
}
else if(i==2){
// For Channels section -- "Set current channel details"
document.getElementById('frame1').contentWindow.opts[selected].setAttribute('name','set');
document.getElementById('frame1').contentWindow.menuSelect(1);
var strValue = document.getElementById('frame1').contentWindow.opts[selected].getAttribute('name');
//alert("Attribute value set :" + strValue);
document.getElementById('frame1').contentWindow.handleKeyCode(VK_ENTER);
i++;
}
}
$(function() {
setInterval(function(){func2();}, 1000);
});
In this the setInterval works only once i.e it executes only the first if condition. But as I enables the "alert" messages of all the conditions then the setInterval works fine.
I don't want the "Alert Messages" for this setInterval if conditions, it should executed each if elseif statment as per the condition and at given time interval.
I am enable to achieve this. Also i didn't find any satisfactory reference from the setInterval related questions in this forum. Please help.
Thanks.
I believe you are getting an exception inside func2 which make it seem like it is not running more than once. Reading .contenWindow when it is null. Try using try/catch to catch the exception. Or use a debugger.

Connection closing after repeater databinding

I recently changed the way the connection worked on my web app and now I'm facing something that I don't understand.
I hava a page that call a function called "ItemGet" in the Page_Load and it work perfectly when there is no data in the first repeater (Repeater1). When I click on a button that reload the page with different data (I know there is data in the repeater), the connection is closed automatically right after that same repeater (Repeater 1). The problem, is that there is another repeater right after (RepeaterTopTen) that need the same connection. I closed manually the connection right after the call to that function but at least I need the connection to stay open during all the function.
Do any of you know the reason why it closed itself and what I can do to prevent it to close at this time?
Here is the code :
private void ItemsGet(string csCategory, string csTimeFrame)
{
DataSet data;
if (csCategory == null)
{
data = m_database.GetPost(Tools.GetPostLang(), Session["TimeFrame"].ToString());
Page.Title = m_database.GetTranslation(509);
}
else
{
data = m_database.GetPost(Convert.ToInt32(csCategory), Tools.GetPostLang(), Session["TimeFrame"].ToString());
Page.Title = m_database.GetTranslation(508) + m_database.GetCategoryName(Convert.ToInt32(csCategory));
}
// Populate the repeater control with the Items DataSet
PagedDataSource objPds = new PagedDataSource();
objPds.DataSource = (DataView)(data.Tables[0].DefaultView);
// Indicate that the data should be paged
objPds.AllowPaging = true;
// Set the number of items you wish to display per page
objPds.PageSize = 5;
// Set the PagedDataSource's current page
if (CurrentPage != 0)
objPds.CurrentPageIndex = CurrentPage;
else
objPds.CurrentPageIndex = 0;
lblCurrentPage.Text = m_database.GetTranslation(423) + (CurrentPage + 1).ToString() + m_database.GetTranslation(422) + objPds.PageCount.ToString();
// Disable Prev or Next buttons if necessary
btnPrev.Enabled = !objPds.IsFirstPage;
btnNext.Enabled = !objPds.IsLastPage;
Repeater1.DataSource = objPds;
Repeater1.DataBind();
DataSet dataTopTen = m_database.GetTopTenUser();
RepeaterTopTen.DataSource = dataTopTen;
RepeaterTopTen.DataBind();
}
Because no one answer that one, I created a function that check if the connection is open and if not, it open it. I checked carefully that it was closed each time.
If you declare your database object and call the open method on the database connection in your Page_Load method, then the database connection will remain open during your entire page life cycle. With your database connection declared in this function, the database object goes out of scope and gets closed when your function ends.

Resources