I am building a web app with C# and asp.net. In the webpage, there is a header with a search bar and a body with a form. When I enter something in the search bar, one of the form fields shows the pop-up, "Please fill out this field".
This field is required, but for the form which has a separate submit button. So what I'm saying is my search button and form are connected but they shouldn't be.
Edit:
Code behind for the search button:
protected void btnOpenModalSearch(object sender, EventArgs e) {
//get information from database to populate the modal box with
PopulateModalBoxGridView();
ScriptManager.RegisterStartupScript(this, this.GetType(), "Properties",
\ "openModal();", true);
}
protected void PopulateModalBoxGridView() {
if (dtSearch == null) return;
//sort the search results in data table
DataView dvSearch = dtSearch.DefaultView;
dvSearch.Sort = SortOrder;
gridSearchResults.DataSource = dvSearch;
gridSearchResults.DataBind();
}
Code behind for the separate form:
protected async void btnCreateNewAsset_Clicked(object objSender, EventArgs evntArgs) {
//create a new asset
//first check for duplicates
if (IsDuplicateAsset()) { return; }
Asset newAsset = new Asset {
//creating asset
};
//post the asset to Team Dynamix
var addAssetUri = new Uri(locationOrigin + webApiBasePath + addAssetPath);
responseMsg = await httpClient.PostAsJsonAsync(addAssetUri, newAsset);
httpResponse = responseMsg.Content.ReadAsStringAsync().Result;
if (!responseMsg.IsSuccessStatusCode) {
Notification.Show(this, "Error. Response content=" + httpResponse, Status.Error);
}
else {
Notification.Show(this, "Successfully Created Asset.", Status.Success);
assetDictionary.Add(serialNumber.Text, serialNumber.Text);
ClearTextFields(frmIndex);
}
}
I found the answer here: HTML 5 required validator triggers on all buttons on the form
To save you the trip, I needed to add formnovalidate="formnovalidate" to my button
<asp:ImageButton ID="BtnSearch" formnovalidate="formnovalidate" data-target="#myModal" ClientIDMode="Static" runat="server" ImageUrl="~/images/search.svg" Text="Search" OnClick="btnOpenModalSearch"></asp:ImageButton>
Related
I'm doing a C# 3-tier project about pets
On load of the first webform I make a query to the database and get the data of all pets (id, name, photo) as a List to be shown as cards with images in HTML, I'm using Materialize by the way, I leave this link as example http://materializecss.com/cards.html
My code behind (Pets.aspx.cs) is this
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
NegPet negPet = new NegPet();
StringBuilder sbHtml = new StringBuilder();
List<EntPet> listEntPet = negPet.getAllPet(5); //5 is the user code (get all pets from user 5)
if (listEntPet.Count > 0)
{
foreach (EntPet entPet in listEntPet)
{
sbHtml.Append("<div class=\"col s6 m4\">");
sbHtml.Append("<div class=\"card\">");
sbHtml.Append("<div class=\"card-image\">");
sbHtml.Append("<img src=\"http://www.dogzone.com/images/breeds/beagle.jpg\" alt=\"\" class=\"circle responsive-img\" />");
sbHtml.Append("<asp:LinkButton id=\"lb_"+ entPet.Id_pet + "\" runat=\"server\" CommandArgument='<%# Eval(\""+ entPet.Id_pet + "\") %>')");
sbHtml.Append("\" click=\"updatePet_Click\" class=\"btn-floating halfway-fab waves-effect waves-light red\"><i class=\"material-icons\">edit</i></a>");
sbHtml.Append("</div>");
sbHtml.Append("<div class=\"card-content\">");
sbHtml.Append("<span class=\"card-title\">");
sbHtml.Append(entPet.Name_pet);
sbHtml.Append("</span>");
sbHtml.Append("</div>");
sbHtml.Append("</div>");
sbHtml.Append("</div>");
}
} else
{
sbHtml.Append("<h2>No pets found</h2>");
}
galPet.Controls.Add(new Literal { Text = sbHtml.ToString() });
}
}
Where galPet is a
<asp:PlaceHolder ID="galPet" runat="server" />
This code returns me all the "Id" and "Name" of "Pets" and sets it in the HTML design that I want, similar to a gallery. The problem comes when I try to get to the event onClick="updatePet_Click" apparently it never reaches it's method behind
public void updatePet_Click(Object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
string yourValue = btn.CommandArgument.Substring(3);
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + yourValue + "');", true);
}
What I'm trying to do with this code is retrieve the ID from the clicked asp:LinkButton so I can use it in code behind
I also tried changing the event to "OnClick" but I got this error when tried to click it
Pets.aspx:24 Uncaught ReferenceError: updatePet_Click is not defined
at HTMLUnknownElement.onclick (Pet.aspx:24)
I would like to know how to retrieve the ID to work it in the code behind or if there is another way to pass my list to the HTML design where I can get the clicked ID easier. Thanks
I'm trying to use a Button to open a link in a new tab in ASP.NET. I'm trying the following but it isn't working:
<asp:Button ID="ReportButton" runat="server" CssClass="button" Font-Size="XX-Large" ForeColor="White" Text="Report" OnClick="ReportButton_Click" OnClientClick="form1.target='_blank';" />
In the code, ReportButton_Click is defined as follows:
protected void SkidPackReportButton_Click(object sender, EventArgs e)
{
GoToPage(LocationSkidPackReportPage);
}
and GoToPage is defined as follows:
bool GoToPage(string page)
{
try
{
Response.Redirect(page);
return true;
}
catch (Exception)
{
StatusLabel.Text = "There was an error finding the page.";
return false;
}
}
Don't do server-side Response.Redirect, just do a client-side window.open. E.g.
void GoToPage(string page) {
ScriptManager.RegisterStartUpScript(this, this.GetType(), "newPage", String.Format("window.open({0});", page), True);
}
Or better yet - avoid postback altogether. You can assign clientClick to your button like:
ReportButton.OnClientClick = String.Format("window.open({0});return false;", LocationSkidPackReportPage);
This way new page will be opened on client without need to go back to the server.
Make LocationSkidPackReportPage a public property in code behind and then replace your button by:
Report
OR, if you need to fill this var in code behind:
// Response.Redirect(page); -> Replace this by:
string script = String.Format("window.open('{0}', '_blank');", LocationSkidPackReportPage);
ScriptManager.RegisterStartUpScript(this, this.GetType(), "reportResultPage", script, True);
this work for me
Page.ClientScript.RegisterStartupScript(
this.GetType(), "OpenWindow", "window.open('../_Reportes/ReporteGeneral.aspx','_newtab');", true);
I have button called sales and it have a JavaScript popup when I click on cancel it postback and the values in the form are inserted but when i click on ok it does not post back and the values in the form does not go in the database ( the JavaScript button is actually print call and when button is clicked it asks for print when print dialog box is open it does not post back and data is not inserted in the database)
here is the javascript code
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
__doPostBack();
}
else {
__doPostBack();
}
}
here is the code for button click
<asp:Button ID="btnaddsale" runat="server" Text="Sale" OnClick="btnaddsale_Click" OnClientClick="javascript:confirmAction('printable')"/>
Ok, couple of notes for you:
You want a postback in either case.
Your <asp:Button> will automatically do a postback either way, so you don't need to call __doPoskBack(); in this scenario.
Major issue here is that, if you want a postback, it will happen immediately when the function exits, effectively canceling out the print dialog too soon. To avoid this, we will use a JavaScript trick that will check if the document has focus, and only when it does (when user exits print dialog in the browser) will we return and allow the postback to occur.
To fix the issue,
First: Make the function return true; when user cancels, and wait for focus and then return true if the user wants to print:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
// Check focus after user exits print dialog and then return true for the postback
var document_focus = false;
$(document).focus(function () { document_focus = true; });
setInterval(function () { if (document_focus === true) { return true; } }, 500);
}
else {
return true;
}
}
Then, change the JavaScript code to use the return statement in the OnClientClick event:
<asp:Button ID="btnaddsale" runat="server" Text="Sale"
OnClick="btnaddsale_Click"
OnClientClick="javascript:return confirmAction('printable')"/>
Update based on comments and your changed requirement:
Here's a snippet to make the script pop up after the postback. So you will insert values to database, and then add the print script / confirm dialog on page load using Page.ClientScript.RegisterStartupScript()
Note I don't recommend to embed the script in your C# code, so I'd suggest to take your confirmAction() function and place it (if not already) into a separate "yourScripts.js" file and then just call the function name when the page is loaded using jQuery. Here's an example:
In your master page or page header: This file should contain the confirmAction() function
<script type="text/javascript src="path/to/yourScriptsFile.js">
Then, in code-behind:
protected void Page_Load(object sender, EventArgs e)
{
// Only display script on PostBack, not initial page load
if (IsPostBack)
{
Page.ClientScript.RegisterStartupScript(
this.GetType(),
"confirmAction",
#"<script type=""Text/Javascript"">$(document).ready(function() { confirmAction('printable'); });</script>");
}
}
Also note, since you will NOT want a postback now, the confirmAction function should no longer return true; or use the trick code I posted above, and will just return false:
function confirmAction(printable) {
var r = confirm("You want to Print Invoice?");
if (r == true) {
var printContents = document.getElementById(printable).innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
return false;
}
I am using Telerik RadControls in my project and and have a menu where I have an 'About' button. When I click the 'About' button a window pops up describing the application. The problem is if I refresh the page or navigate to another page then back to the first page the window automatically pops up.
The goal is only have that window pop up when the user clicks the about button.
here is the code I used to get that window:
<!--About Window-->
<telerik:RadWindowManager runat="server" EnableViewState="false" KeepInScreenBounds="true"></telerik:RadWindowManager>
<telerik:RadWindow ID="AboutMenu" Behaviors="Close" Animation="None" runat="server" Width="360px" KeepInScreenBounds="true" Height="360px" Modal="true" VisibleStatusbar="false" Skin="Glow">
<ContentTemplate>
<p style="text-align: center;">Sample Window Information</p>
</ContentTemplate>
</telerik:RadWindow>
Javascript
function OnClientItemClick(sender, eventArgs) {
if (window.args.get_item().get_text() == "About") {
var radwindow = window.$find(window.AboutMenu.ClientID);
window.args.set_cancel(true);
}
}
.cs
protected void MainMenu_OnItemClick(object sender, RadMenuEventArgs e)
{
if (e.Item.Text == "About")
{
AboutMenu.VisibleOnPageLoad = true;
}
}
The window works but it loads whenever the page loads and thats where I think the line AboutMenu.VisibleOnPageLoad = true comes into play and is causing the error but when I take out that line it won't display at all.
Instead of using VisibleOnPageLoad try using the following code to open the window on itemclick.
protected void MainMenu_OnItemClick(object sender, RadMenuEventArgs e)
{
if (e.Item.Text == "About")
{
string script = "function f(){$find(\"" + RadWindow1.ClientID + "\").show(); Sys.Application.remove_load(f);}Sys.Application.add_load(f);";
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "key", script, true);
}
}
Or, just use the OnCLientItemClicking event of the menu to open the RadWindow and cancel the postback. But you will need to fix you JS code, because the arguements are in the context of the current function. ALso, the reference to RW may break unless you have made your own array of ClientIDs.
function OnClientItemClicking(sender, eventArgs) {
if (eventArgs.get_item().get_text() == "About") {
var radwindow = window.$find(<%=AboutMenu.ClientID%>);
radwindow.show();
eventArgs.set_cancel(true);
}
}
I need to show Sharepoint 2010 like pop-up window when clicked on a link in grid view. Once the modal pop-up displayed and user selected the Save button data base should be updated with given values in pop-up. How can I get this. Any Idea.
As of now I am using below code to get it but no idea how to pass the values to Database once clicked on the button in pop-up
Note: As of now I am not adding the gridview code here as I wanted to achieve it first with sample html then wanted to do with grid view.
Java Script
function openDialog() {
var options = {
html: divModalDialogContent, // ID of the HTML tag
// or HTML content to be displayed in modal dialog
width: 600,
height: 300,
title: "My First Modal Dialog",
dialogReturnValueCallback: dialogCallbackMethod, // custom callback function
allowMaximize: true,
showClose: true
};
SP.UI.ModalDialog.showModalDialog(options);
}
//Results displayed if 'OK' or 'Cancel' button is clicked if the html content has 'OK' and 'Cancel' buttons
function onDialogClose(dialogResult, returnValue) {
if (dialogResult == SP.UI.DialogResult.OK) {
alert('Ok!');
}
if (dialogResult == SP.UI.DialogResult.cancel) {
alert('Cancel');
}
}
// Custom callback function after the dialog is closed
function dialogCallbackMethod() {
alert('Callback method of modal dialog!');
}
HTML
<div id="divModalDialogContent">
Hello World!
<input type="button" value="OK"onclick="SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.OK, 'Ok clicked'); return false;"
class="ms-ButtonHeightWidth" />
<input type="button" value="Cancel"onclick="SP.UI.ModalDialog.commonModalDialogClose(SP.UI.DialogResult.cancel, 'Cancel clicked'); return false;"
class="ms-ButtonHeightWidth" />
<asp:Button runat="server" ID="btnClicked" Text="Clicked"
onclick="btnClicked_Click" />
<input type="button" value="Open" onclick="openDialog()" />
How can I call db upon clicking 'clicked' button in pop-up. Also I need to send parameters to pop-up
Thanks in advance
If you need ok, cancel or submit button event on popup screens which interacts with Sharepoint list/library or sql database then you need to implement event in your popup. Check below steps:-
your popup page should inherit "Microsoft.SharePoint.WebControls.LayoutsPageBase"
which should have this function:-
protected void EndOperation(int result, string returnValue)
{
string closeModal = String.Format(CultureInfo.InvariantCulture,
"<script type=\"text/javascript\">window.frameElement.commonModalDialogClose
({0}, '{1}');</script>", new object[] { result, returnValue });
this.Page.ClientScript.RegisterStartupScript(base.GetType(),
"CreatePopup", closeModal, false);
}
Implement an event which can be listen on popup action like ok button
public delegate void AddEventHandlerToSPDialogEvent(object sender, PDialogEventHandler e);
public class SPDialogEventHandler : EventArgs
{
public int dialogResult { get; set; } // 0 or 1
public string ReturnValues { get; set; } // can be url or any success/error message
public SPDialogEventHandler(int result, string list)
{
ReturnValues = list;
dialogResult = result;
}
}
Call this event from your button action in popup. for ex:
public event AddEventHandlerToSPDialogEvent ResultOk;
protected void CancelBtn_Click(object sender, EventArgs e)
{
try
{
int dialogResult = 0;
if (this.ResultOk != null)
{// Here dialogResult is 0. that means we have clicked on cancel button
ResultOk(this, new SPDialogEventHandler(dialogResult,"Action Cancelled"));
}
}
catch (Exception ex) { }
}
You can use the Ajax control toolkit, then you should look for the modal popup extender.
Like that you can add .net controls into the overlay/modal overlay and get the values in code behind
for more info see here
http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ModalPopup/ModalPopup.aspx
SP Popup
Open a modal/pop up form in Sharepoint 2010 with asp.net controls in it