open a fancybox on pageload - c#

The situation is to open a fancy box on the page load,
Please find the below html, and the code behind I am using but with no success.
protected void Page_Load(object sender, EventArgs e)
{
if (SessionController.CurrentMember != null)
{
if (Request.IsAuthenticated)
{
int memberId = SessionController.CurrentMember.MemberID;
bool checkaccepted = CheckAcceptedTermsandConditions(memberId);
if (!checkaccepted)
{
string script = #"<script>$(document).ready(function() {
$(""#onlineCasinoTandC"").fancybox({
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'speedIn' : 600,
'speedOut' : 200,
'overlayShow' : false,
'overlayOpacity': 0.5,
'width' : 800,
'showCloseButton': true,
});
$(""#onlineCasinoTandC"").click();
});</script>";
ClientScript.RegisterStartupScript(this.GetType(), "fancybox", script);
onlineCasinoTandC.HRef = "/Common/EN/TermsandConditions.aspx";
}
}
}
}
Regards
Srividhya

delete the extra comma at the end of this line
'showCloseButton': true
And if u want to trigger, Click event, it should be
$('#foo').trigger('click');

Please find the below solution.
on page load
string script = #"<script type=""text/javascript"">$(document).ready(function() {$(""#termsandConditions"").fancybox({'transitionIn':'elastic','transitionOut':'elastic','speedIn':600,'speedOut':200,'overlayShow':false,'overlayOpacity': 0.5,'width':800,'href':""/Contents/Common/EN/TermandConditions.aspx""}).trigger('click');});</script>";
Type cstype = this.GetType();
ClientScriptManager cs = Page.ClientScript;
if (!cs.IsStartupScriptRegistered(cstype, script))
{
cs.RegisterStartupScript(cstype, "fancybox", script);
}
Regards
Vidya

Related

DotNetNuke WebForm Alert Dialog box

I am currently developing a DotNetNuke module. However, I failed to prompt user an alert dialog box in certain situations like record duplication.
I am using the following code to display an alert box in Controller class.
EditForm edForm = new EditForm();
ScriptManager.RegisterClientScriptBlock(edForm, edForm.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
The following is my full code.
Form.ascx.cs
void cmdUpdate_Click(object sender, EventArgs e)
{
UdtController.UpdateRow(Data, ModuleId, False);
}
UdtController.cs
public void UpdateRow(DataSet ds, int rowNr, bool isDataToImport)
{
var values = new Dictionary<int, string>();
string strIsUnique = "";
foreach (DataRow field in ds.Tables[DataSetTableName.Fields].Rows)
{
var strColumnName = field[FieldsTableColumn.Title].ToString();
strIsUnique = field[FieldsTableColumn.Searchable].ToString();
var strValueColumn = ((!isDataToImport &&
ds.Tables[DataSetTableName.Data].Columns.Contains(strColumnName +
DataTableColumn.
Appendix_Original))
? strColumnName + DataTableColumn.Appendix_Original
: strColumnName);
if (strIsUnique == "True")
{
int uniqueDataCount = FieldController.uniqueData(currentRow[strValueColumn].AsString());
if (uniqueDataCount == 0)
{
if (ds.Tables[DataSetTableName.Data].Columns.Contains(strValueColumn))
{
values.Add(field[FieldsTableColumn.Id].AsInt(), currentRow[strValueColumn].AsString());
}
}
else
{
EditForm edForm = new EditForm();
ScriptManager.RegisterClientScriptBlock(edForm, edForm.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
break;
}
}
else
{
if (ds.Tables[DataSetTableName.Data].Columns.Contains(strValueColumn))
{
values.Add(field[FieldsTableColumn.Id].AsInt(), currentRow[strValueColumn].AsString());
}
}
}
FieldController.UpdateData(userDefinedRowId, values);
}
You need to reference the Page, not create a new form.
Page page = HttpContext.Current.CurrentHandler as Page;
ScriptManager.RegisterStartupScript(page, page.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);
However DNN has it's own message box you could use:
http://uxguide.dotnetnuke.com/UIPatterns/AlertDialog.html

How to show a error message when wrong file uploaded other than(jpeg) in ajax_uploadfile asp.net using jquery?

I am working on ASP.NET ajax_uploadfile here I need to show a error message I had given AllowedFileTypes="jpg,jpeg,png"
Here is my code:
<asp:AjaxFileUpload runat="server" ThrobberID="Throbber"
ID="upFile" AllowedFileTypes="pdf" Onchange="Callingerrormesage()"
MaximumNumberOfFiles="5" OnClientUploadComplete="File_Upload" />
Here is my script code:
<scrpt>
function Callingerrormesage(){
alert(1);
}
</script>
Here is my code behind:
protected void File_Upload(object sender, AjaxFileUploadEventArgs e)
{
string filename = e.FileName;
string strDestPath = Server.MapPath("~/Documents/");
AjaxFileUpload1.SaveAs(#strDestPath + filename);
}
when I uploaded the jpeg file it's working fine when I need to upload the other than the jpeg file
I need to show the error message like
I had given Onchange="Callingerrormesage()" not working could you please help me on this?
You should validate BEFORE uploading like this:
$("input:file").change(function () {
if ($(this).val() !== "") {
var ul_file = $(this).val();
var extension = ul_file.substr((ul_file.lastIndexOf('.') + 1));
var accepted_file_endings = ["jpg", "jpeg"];
extension = extension.toLowerCase()
if ($.inArray(extension, accepted_file_endings) !== -1) {
...
//send file
protected void File_Upload(object sender, AjaxFileUploadEventArgs e)
{
string filename = e.FileName;
string strFileExtension = System.IO.Path.GetExtension(strLongFilePath);
if(strFileExtension=="jpg")
{
Your code here
}
else
{
session["error"]="Your error message";
}
and retrive the session value at your page...

How to use ScriptManager in class file?

I Have a common method that displays alert message using page.clientScript. But later on i added update panel. Now this piece of code is not working. So I need to call there scriptmanager, but i get some error message that it is accessible there.
Below is my ShowMessage method of common.cs file
private static void ShowMessage(Page currentPage, string message)
{
var sb = new StringBuilder();
sb.Append("alert('");
sb.Append(message);
sb.Append("');");
currentPage.ClientScript.RegisterClientScriptBlock(typeof(Common), "showalert", sb.ToString(), true);
}
So how do I use this method under update panel
Make use of : ScriptManager.RegisterClientScriptBlock Method
ScriptManager.RegisterClientScriptBlock(
this,
typeof(Page),
"TScript",
script,
true);
const string scriptString = "<script type='text/javascript'> alert('message');</script>";
ClientScriptManager script = Page.ClientScript;
script.RegisterClientScriptBlock(GetType(), "randomName", scriptString);
For use in a class file:
public static void SendAlert(string sMessage)
{
sMessage = "alert('" + sMessage.Replace("'", #"\'").Replace("\n", #"\n") + "');";
if (HttpContext.Current.CurrentHandler is Page)
{
Page p = (Page)HttpContext.Current.CurrentHandler;
if (ScriptManager.GetCurrent(p) != null)
{
ScriptManager.RegisterStartupScript(p, typeof(Page), "Message", sMessage, true);
}
else
{
p.ClientScript.RegisterStartupScript(typeof(Page), "Message", sMessage, true);
}
}
}
This could be expanded to include other possible handlers, but for the moment this is how I solved the problem.
Try this in .cs file
var page = HttpContext.Current.CurrentHandler as Page;
ScriptManager.RegisterStartupScript(page, page.GetType(), "alert", "alert('Success');window.location ='Home.aspx';", true);
It's working for me ^^
Here's how I did it:
public partial class JQuery
{
private Page page;
public JQuery(Page pagina) {
page = pagina;
}
public void Alert(string Title, string Message)
{
Message = Message.Replace("\n", "<br>");
string command = String.Format("myCustomDialog('{0}','{1}')", Title, Message);
ScriptManager.RegisterClientScriptBlock(page, this.GetType(), "", command, true);
}
}
Then you can use like this:
JQuery jquery = new JQuery(this.Page);
jQuery.Alert("Title", "Look, a jQuery dialog!");

C# Web browser control is not updating correctly

I'm currently working on an app that technically interacts with an html page that uses dynamic content.
My problem is when I try to append data to the WBC the content isn't updating correctly.
namespace CheckList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
.... code removed ....
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != null)
{
HtmlDocument doc = webBrowser1.Document;
HtmlElement row = doc.CreateElement("tr");
HtmlElement cell1 = doc.CreateElement("td");
HtmlElement cell2 = doc.CreateElement("td");
cell1.InnerHtml = "[X] " + textBox1.Text;
cell2.SetAttribute("class", "solved_2");
cell2.InnerHtml = "Unsolved";
row.AppendChild(cell1);
row.AppendChild(cell2);
doc.GetElementsByTagName("table")[0].AppendChild(row);
//doc.Write(doc.GetElementsByTagName("HTML")[0].OuterHtml);
webBrowser1.Document.Body.InnerHtml = doc.Body.InnerHtml;
}
}
}
}
What currently happens is, I click "add" it should add the html to the page and update and the javascript and what not should still load.
What happens is it adds the content, but the javascript doesn't work after I attempt to reload the content. The CSS stays in tact though, and the javascript isn't working after that point.
JS Source:
var showalert = true;
var file = "file:///C:/Users/Removed/Documents/Visual Studio 2010/Projects/CheckList/CheckList/bin/Release/";
initiate_instance();
function initiate_instance() {
//insert
$.get(file + "saved.html", function(data) {
//$("table#items").append("<tr><th width='70%'>Issue</th><th width='30%' class='right'>Solved</th></tr>");
$("table#items").html($("table#items").html() + data);
});
//change [X] into a link
$("table#items tr td").each(function() {
$(this).html($(this).html().replace("[X]", "<a onclick='return remove(this)' href='#'>[X]</a>"));
});
//change the css
$("table#items tr:odd").attr("class", "odd");
$("table#items tr td:eq(0)").attr("width", "70%");
$("table#items tr td:eq(1)").attr("width", "30%");
$("td.solved, td.solved_2").click(function() {
if($(this).attr("class") == "solved") {
$(this).attr("class", "solved_2");
$(this).text("Unsolved");
} else {
$(this).attr("class", "solved");
$(this).text("Solved");
}
if(showalert == true) {
alert("Remember, for these changes to keep effect please save before closing the program.");
showalert = false;
}
});
}
//delete rows
function remove(obj) {
if(showalert == true) {
alert("Remember, for these changes to keep effect please save before closing the program.");
showalert = false;
}
$(obj).parent().parent().remove();
return false;
}
TL;DR: Have you tried setting "AllowNavigation" to true?
If you need to prevent navigation, but still need to update the page, a method I've found that works requires:
Initializing the WebBrowser control's DocumentText property with empty HTML to initialize the internal objects (i.e.: Document, DomDocument, Document.Body, etc)
Allowing navigation and the revoking upon page completion (if needed)
Code:
namespace CheckList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Initialize all the document objects
webBrowser1.DocumentText = #"<html></html>";
// Add the Document Completed event handler to turn off navigation
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Load default information via LoadHtml(string html);
LoadHtml(#"<html><head></head><body>Text!<script type='text/javascript' language='javascript'>alert('Aha!');</script></body></html>");
}
private void LoadHtml(string html)
{
webBrowser1.AllowNavigation = true;
// This will trigger a Document Completed event
webBrowser1.DocumentText = html;
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Prevent further navigation
webBrowser1.AllowNavigation = false;
// Clean-up the handler if no longer needed
}
private void button2_Click(object sender, EventArgs e)
{
// Do your document building
LoadHtml(doc.Body.Parent.OuterHtml);
}
}
}
I've found doing it this way:
Prevents users from navigating until allowed
Allows execution of JavaScript (immediately before OnDocumentCompleted fires)

how can i get the same page with the click of back button of browser

i am using asp.net with c# in my aspx page i have an update panel in this panel i have some links to other sites, which is open on the same window. after clicking on these links me when i am getting back through browser's back button i am not getting the same results on the update panel...
I have implement the same with the following Article, If you need further help, Plz let me know, I will provide chucks of code
http://rchern.wordpress.com/2008/05/11/updatepanel-backforward-browser-navigation/
First of all you have to Enable ScriptManager history EnableHistory="true"
In this example we are maintaing gridview paging, When user browser back button
You have add history point after your page first time loads.
private void AddHistoryPoint(String key, String value, String tile)
{
ScriptManager scm = ScriptManager.GetCurrent(this.Page);
if ((scm.IsInAsyncPostBack == true) && (scm.IsNavigating != true))
{
if (pageState == null)
{
NameValueCollection pageState = new NameValueCollection();
}
if (pageState[key] != null)
{
pageState[key] = value;
}
else
{
pageState.Add(key, value);
}
scm.AddHistoryPoint(pageState, tile);
}
}
protected void grid_PageIndexChanged1(object sender, EventArgs e)
{
AddHistoryPoint("pi", grdProject.PageIndex.ToString(), "Page Index- " + (grdProject.PageIndex + 1).ToString());
}
here you have to handle ScriptManager Navigate Event
protected void ScriptManager1_Navigate(object sender, System.Web.UI.HistoryEventArgs e)
{
if (e.State != null)
{
if (e.State["pi"] != null)
{
grid.PageIndex = Convert.ToInt32(e.State["pi"]);
}
}
}

Categories