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
Related
After doing lots of debugging, I've narrowed down as to why my dbContext update does not work.
I have a script that runs on Page_Load that will populate a form based on the query string category_Id which is the primary key of my table.
protected void Page_Load(object sender, EventArgs e)
{
// Populate Edit Fields
if (Request.QueryString["categoryId"] != null)
{
CategoryDAL categoryDAL = new CategoryDAL();
RecipeCategory myCategory = new RecipeCategory();
try
{
addDiv.Attributes["class"] = "hidden";
editDiv.Attributes["class"] = "display";
int categoryToGet = Convert.ToInt32(Request.QueryString["categoryId"]);
myCategory = categoryDAL.GetCategory(categoryToGet);
tbEditCategoryName.Text = myCategory.Category_Name;
tbEditCategoryDescription.Text = myCategory.Description;
ddlEditCategoryGroupList.SelectedValue = Convert.ToString(myCategory.CatGroup_Id);
ddlEditCategoryGroupList.DataBind();
}
catch(Exception ex)
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Could not get Category Info, please try again.";
}
}
This is my script that runs when the edit_Button is clicked, it should update the row in the database and redirect to the viewCategories page.
protected void btnEditCategory_Click(object sender, EventArgs e)
{
if (Request.QueryString["categoryId"] != null)
{
CategoryDAL categoryDAL = new CategoryDAL();
RecipeCategory myCategory = new RecipeCategory();
try
{
int categoryToEdit = Convert.ToInt32(Request.QueryString["categoryId"]);
myCategory.Category_Name = tbEditCategoryName.Text;
myCategory.Description = tbEditCategoryDescription.Text;
myCategory.CatGroup_Id = Convert.ToInt32(ddlEditCategoryGroupList.SelectedValue);
try
{
bool editStatus = categoryDAL.EditCategory(categoryToEdit, myCategory);
if (editStatus)
{
HttpContext.Current.Session["editStatus"] = "Successful";
Response.Redirect("~/Admin/ManageCategories.aspx");
}
else
{
lblEditStatus.Text = "Unable to update category, please try again";
lblEditStatus.CssClass = "alert-danger";
}
}
catch (Exception ex)
{
lblEditStatus.Text = Convert.ToString(ex);
lblEditStatus.CssClass = "alert-danger";
}
}
catch (Exception ex)
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Invalid categoryId.";
}
}
else
{
updateStatus.Attributes["class"] = "alert alert-info alert-dismissable fade in";
updateStatus.Visible = true;
lblStatus.Text = "Nothing to update.";
}
}
And this is in my DALayer which holds the functions that has anything to do with categories.
public bool EditCategory(int categoryToEdit, RecipeCategory newCategoryInfo)
{
RecipeXchangeDBContext dbContext = new RecipeXchangeDBContext();
RecipeCategory myCategory = new RecipeCategory();
bool status = false;
myCategory = (from c in dbContext.RecipeCategories
where c.Category_Id == categoryToEdit
select c).First();
myCategory.Category_Name = newCategoryInfo.Category_Name;
myCategory.Description = newCategoryInfo.Description;
myCategory.CatGroup_Id = newCategoryInfo.CatGroup_Id;
try
{
if (dbContext.SaveChanges() == 1)
status = true;
else
status = false;
}
catch (InvalidOperationException ex)
{
status = false;
}
return status;
}
For some reason, whenever I try to update a row with a prepopulated form, the code will always return 0 from dbContext.SaveChanges() and does not update the row in the database.
Note: if I do not populate the form, it works perfectly as normal.
Page_Load doesn't just run the first time the page is loaded, it runs every time the page is loaded, including when the user submits the form. The result is that you're overwriting the user's input before saving it.
In this case, since you're using regular browser navigation to go to a specific category page, you can just check Page.IsPostBack in Page_Load and not set anything in that case.
How to call a conditional confirm box from c#.
I have 2 hidden fields and based on the condition I want to call confirm box.
After that I also want what user has pressed (clicked on yes or No).
Design:-
<input type="submit" id="btnAddPaymentMethod" onserverclick="AddPaymentMethod_Click" runat="server" value="add payment method" />
Code:-
protected void Next_Click(object sender, EventArgs e)
{
if (hdnDefault.Value == hdnPrimary.Value) { return; }
else
{
//open confirm box
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "confirm('Do you want to save new default payment method?');", true);
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true);
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!')", true);
}
}
}
I have tried below jQuery Code:-
function Confirm(msg) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm(msg)) {
confirm_value.value = "Yes";
$('#btnAddPaymentMethod').click();
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
protected void Next_Click(object sender, EventArgs e)
{
if (hdnDefault.Value == hdnPrimary.Value) {
return;
} else {
//open confirm box
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "confirm", "Confirm('Do you want to save new default payment method?');", true);
}
}
protected void AddPaymentMethod_Click(object sender, EventArgs e)
{
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes") {
ScriptManager.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true);
} else {
ScriptManager.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!')", true);
}
}
function Confirm(msg) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
confirm_value.value = confirm(msg)? "Yes" : "No";
document.forms[0].appendChild(confirm_value);
$('#btnAddPaymentMethod').click();
}
I have not run your code. But when you have runat="server" for an input control it will append with the asp.net unique Id. So try to access the input control by it's name ending with btnAddPaymentMethod as below.
Change from $('#btnAddPaymentMethod').click(); to $('[id$=btnAddPaymentMethod]').click();
This jQuery code will open a confirm dialog, with an 'ok' and 'cancel' buttons.
Here an anchor tag with an id of myConfirmPageLink, when clicked, will ask for confirmation. If ok is clicked it proceeds to the target, and if cancel is clicked it stays on the same page.
$("a#myConfirmPageLink").click(function(){
return confirm("Are you sure you want to go to that page/site ?");
});
This should be easy to modify for your purposes.
Im having a problem handing an exception in ASP.net WebForms(i'm a beginner)
i want to display the error in the webform using CustomValidator but with no luck, below is my code.
protected void dvEmployeeList_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
GridViewRow rowSelect = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
int rowindex = rowSelect.RowIndex;
string confirmValue = Request.Form["confirm_value"];
if (confirmValue == "Yes")
{
try
{
int empID;
empID = int.TryParse(dvEmployeeList.DataKeys[rowindex].Value.ToString(), out empID) ? empID : 0;
oEmployeeBLL.DeleteEmployee(empID);
dvEmployeeList.DataSource = oEmployeeBLL.GetEmployeeList();
dvEmployeeList.DataBind();
}
catch (Exception ex)
{
var delConstrainsVal = new CustomValidator();
delConstrainsVal.IsValid = false;
delConstrainsVal.ErrorMessage = "Update failed: " + ex.Message;
delConstrainsVal.Text = delConstrainsVal.ErrorMessage;
Page.Validators.Add(delConstrainsVal);
}
}
else
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('User cancel!')", true);
}
}
it catch the exception but didnt display the message on the on the form.
Please guide me, thanks!
Validators are meant to validate user input, not to display server errors. You should consider using a simple <asp:Label>.
The reason why the error doesn't appear is probably because validation happens before the control is added.
So, here is the scenarion
I have a webpart that loads some data.
I have in another place of the page a button, that opens a popup, when the user does something in that page (create action), the popup is closed and the calling page is reloaded.
When this happen, I can see in the browser that the page is reloaded, but my new data is not shown on the webpart.
I am binding the data in the create child controls, I tried to do it in the page load but then it doesnt work.
If I put my cursor on the address bar then it shows me the new data, but if I press F5 it doesnt.
public class LastCreatedJobs : WebPart
{
private GridView _lastCreatedJobsGrid;
protected override void CreateChildControls()
{
base.CreateChildControls();
CreateGridControl();
}
private void CreateGridControl()
{
try
{
_lastCreatedJobsGrid = new GridView();
_lastCreatedJobsGrid.RowDataBound += _lastCreatedJobsGrid_RowDataBound;
var bJobCode = new BoundField { DataField = "JobCode", HeaderText = "Job Code" };
bJobCode.ItemStyle.CssClass = "ms-cellstyle ms-vb2";
bJobCode.HeaderStyle.CssClass = "ms-vh2";
_lastCreatedJobsGrid.Columns.Add(bJobCode);
var jobName = new HyperLinkField
{
DataNavigateUrlFields = new[] { "JobWebsite" },
HeaderText = "Job Name",
DataTextField = "JobName"
};
jobName.ItemStyle.CssClass = "la";
jobName.HeaderStyle.CssClass = "ms-vh2";
jobName.ControlStyle.CssClass = "ms-listlink";
_lastCreatedJobsGrid.Columns.Add(jobName);
var biPowerLink = new HyperLinkField
{
Target = "_blank",
DataNavigateUrlFields = new[] { "IPowerLink" },
HeaderText = "iP Link",
Text = #"<img src='" + ResolveUrl("/_layouts/15/PWC/DMS/Images/iclient.gif") + "' /> "
};
biPowerLink.ItemStyle.CssClass = "ms-cellstyle ms-vb-icon";
biPowerLink.HeaderStyle.CssClass = "ms-vh2";
_lastCreatedJobsGrid.Columns.Add(biPowerLink);
_lastCreatedJobsGrid.CssClass = "ms-listviewtable"; //Table tag?
_lastCreatedJobsGrid.HeaderStyle.CssClass = "ms-viewheadertr ms-vhlt";
_lastCreatedJobsGrid.RowStyle.CssClass = "ms-itmHoverEnabled ms-itmhover";
_lastCreatedJobsGrid.AutoGenerateColumns = false;
_lastCreatedJobsGrid.EmptyDataText = Constants.Messages.NoJobsFound;
Controls.Add(_lastCreatedJobsGrid);
LoadGridData();
}
catch (Exception ex)
{
LoggingService.LogError(LoggingCategory.Job, ex);
}
}
private void _lastCreatedJobsGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
JobInfo jobInfo = (JobInfo)e.Row.DataItem;
if (jobInfo.IsConfidential)
{
var newHyperLink = new HyperLink
{
Text = #"<img src='" + ResolveUrl("/_layouts/15/PWC/DMS/Images/spy-icon.gif") + "' /> ",
NavigateUrl = jobInfo.xlink
};
e.Row.Cells[2].Controls.RemoveAt(0);
e.Row.Cells[2].Controls.Add(newHyperLink);
}
}
}
catch (Exception ex)
{
LoggingService.LogError(LoggingCategory.Job, ex);
}
}
#region Private methods
private void LoadGridData()
{
try
{
String currentUrl = SPContext.Current.Site.Url;
var jobInfoList = new List<JobInfo>();
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (var clientSiteCollection = new SPSite(currentUrl))
{
foreach (
SPWeb web in
clientSiteCollection.AllWebs.Where(
c =>
c.AllProperties[Constants.WebProperties.General.WebTemplate] != null &&
c.AllProperties[Constants.WebProperties.General.WebTemplate].ToString() ==
Constants.WebTemplates.JobWebPropertyName).OrderByDescending(d => d.Created).Take(5)
)
{
SPList jobInfoListSp = web.Lists.TryGetList(Constants.Lists.JobInfoName);
if (jobInfoListSp != null)
{
if (jobInfoListSp.Items.Count > 0)
{
var value =
new SPFieldUrlValue(
jobInfoListSp.Items[0][Constants.FieldNames.Job.iPowerLink].ToString());
jobInfoList.Add(new JobInfo
{
JobName = jobInfoListSp.Items[0][Constants.FieldNames.Job.JobName].ToString(),
JobCode = jobInfoListSp.Items[0][Constants.FieldNames.Job.JobCode].ToString(),
xlink= value.Url,
JobWebsite = web.Url,
IsConfidential = HelperFunctions.ConvertToBoolean(jobInfoListSp.Items[0][Constants.FieldNames.Job.Confidential].ToString())
});
}
}
web.Dispose();
}
}
});
_lastCreatedJobsGrid.DataSource = jobInfoList;
_lastCreatedJobsGrid.DataBind();
}
catch (Exception ex)
{
LoggingService.LogError(LoggingCategory.Job, ex);
}
}
#endregion
}
and the page that opens the popup:
<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<SharePoint:ScriptLink ID="ScriptLink1" runat="server" Name="sp.js" OnDemand="false" Localizable="false" LoadAfterUI="true"/>
<script type="text/javascript">
//Just an override from the ClientField.js - Nothing Special to do here
function DisableClientValidateButton() {
}
function waitMessage() {
window.parent.eval("window.waitDialog = SP.UI.ModalDialog.showWaitScreenWithNoClose('Creating Job','Working on the Job site. Please wait.',90,450);");
}
</script>
</asp:Content>
and the code behind of that page, in a button click, just the important part, after the button is clicked.
ClientScript.RegisterStartupScript(GetType(), "CloseWaitDialog",
#"<script language='javascript'>
if (window.frameElement != null) {
if (window.parent.waitDialog != null) {
window.parent.waitDialog.close();
window.frameElement.commonModalDialogClose(1, 'New call was successfully logged.');
}
}
</script>");
The trick here is that the loadgrid data has to be executed in the OnPreRender.
When the user clicks on the "Export to Excel" link, the standard "File download" dialog is presented to the user. See here for an example image.
But before exporting the excel file, I want to display an alert popup. But the Save dialog is obscuring the view of the alert popup.
How can I display the popup without it being obscured?
Here is my code...
dsResult = clsObj.getSearchResults_BL(detObj);
if (OrdDifference != null && OrdDifference.Any())
{
ScriptManager.RegisterClientScriptBlock(this.up, this.GetType(), "export", "alert('.....')", true);
set(dsResult, strName);
}
else
{
set(dsResult, strName);
}
private void set(DataSet ds, string strFileName)
{
ExcelEngine excelEngine = new ExcelEngine();
IApplication application = excelEngine.Excel;
application.DefaultVersion = ExcelVersion.Excel2007;
IWorkbook workbook = application.Workbooks.Create(1);
IWorksheet sheet = workbook.Worksheets[0];
try
{
sheet.Name = strFileName;
sheet.ImportDataTable(ds.Tables[0], true, 1, 1, -1, -1);
...
workbook.SaveAs(strFileName, ExcelSaveType.SaveAsXLS, HttpContext.Current.Response, ExcelDownloadType.PromptDialog);
}
catch (Exception ex)
{
}
}
Your problem is here:
ScriptManager.RegisterClientScriptBlock(this.up, this.GetType(), "export", "alert('.....')", true);
set(dsResult, strName);
Because the set method in your program is writing to the Response Stream the call to ScriptManager.RegisterClientScriptBlock ends up doing nothing.
You need to do this on two steps:
if (OrdDifference != null && OrdDifference.Any())
{
//Just do this, nothing more.
ScriptManager.RegisterClientScriptBlock(this.up, this.GetType(), "export", "alertUser('Some Message Here')", true);
}
Now define the alertUser function in Javascript:
function alertUser(message)
{
alert(message);
window.location='AccepServiceOrder.aspx?o=Export';
}
Now on Page_Load check for the o parameter in the query string
protected void Page_Load(object sender, EventArgs e)
{
if(Request.QueryString["o"]!=null)
{
dsResult = clsObj.getSearchResults_BL(detObj);
set(dsResult, strName);
}
}