C# OnCommand Call Alert Box - c#

I have a page which lists a bunch of items in a datagrid.
Each item has a cooresponding remove link button, which removes the item from the list. In my event handler -- where the item is deleted -- I do a check to see if the item is the last item in the list. If it is the last item, I don't do a delete, but send an alert box telling the user that the item cannot be deleted. I am unsure how to get C# to trigger this alert box.
My code looks like the following:
In my aspx, I have a datagrid with various Link Buttons. Snippet of code as shown:
<ItemTemplate>
<asp:LinkButton runat="server" ID="Remove"
OnCommand="lnkRemove_Command" CommandArgument='<%# Eval("Id") %>
OnClientClick="return false;">
</asp:LinkButton>
</ItemTemplate>
In my code behind, my event handler looks like such:
private List<MyItem> _items;
protected void lnkRemove_Command(object sender, CommandEventArgs e)
{
int ID = Convert.ToInt32(e.CommandArgument);
MyItem item = MyItem.GetItemByID(id); //This gets the item cooresponding to the ID
if (_items.Count != 1)
{
//code to delete item
}
else
{
//Generate an alert box to tell the user that this item cannot be deleted.
//I have tried the following two lines of commented code, which didn't work for me
//Response.Write(#"<script language='javascript'>alert('HERE');</script>");
//Page.ClientScript.RegisterStartupScript(this.GetType(), "hwa", "alert('Hello World');", true);
}
}
In addition, it may be important to note that in my Page_Load, I already do a Context.RegisterResource(this, StyleSheet, Script). In other words, I have working JavaScript and CSS, which cooresponds with this code for other features of this page in MyFile.js
If possible, I would like to create a JS function in MyFile.js where I already have js functions which are triggered by various OnClientClicks, etc...
Is it possible to do something like this:
in MyFile.js
var GetAlertMessage = function()
{
alert("Can't delete this item");
}
and call this function in my C# function that I listed above?
Thanks in advance for the help.

You should treat this like any other validation routine. There should be a client-side validation function and a server-side validation function.
Client Side Validation
on each delete-able item, add an onclick="ValidateDeletion();" and class="deleteable-item"
function ValidateDeletion()
{
var itemCount = $(".deleteable-item").length;
if(itemCount == 1)
{
alert("Sorry, you cant delete this item.")
return false;
}
else
{
//let it pass through
}
}

Related

Calling a server side method from a dynamically generated button inside an update panel

Lets preface this with the fact that I am learning ASP.NET C# and this is my first "real" project so there is a good chance I am missing something obvious, I apologize in advance.
I am working on a web page that displays three columns. The first is "Categories", a user should be able to select a category then have a list of items to choose from appear in the second column "Items". When they click an item the third column should show details about said item. For the most part this is a classic Master/Detail scenario except we take it a step further and do Master/Detail/Detail.
To achieve this I am generating dynamic buttons on Page_Load() in the "Categories" column. In addition I have added a debug line when the page loads, this is important later.
protected void Page_Load(object sender, EventArgs e)
{
//DB query to get categories omitted
for (int i = 0; i < categories.Rows.Count; i++)
{
Button btn = new Button();
btn.Click += new System.EventHandler(CategorySelected_Click);
btn.Attributes["runat"] = "server";
btn.ID = "CatSelBtn" + i;
btn.Attributes["data-categoryid"] = qry.GetCategories().Rows[i]["id"].ToString();
//And some other non-relevant attributes
CategoriesPane.Controls.Add(btn);
}
System.Diagnostics.Debug.WriteLine("Page Loaded");
}
As you may have noticed these buttons have a Click event handler that calls the method CategorySelected_Click(). These buttons all generate successfully and clicking on them results in that method being successfully called. This method is set up in a similar fashion, it grabs a list of items then generates buttons for the items, of course this needs to be done asynchronously so it doesn't reset the user's category selection, so this time it is all contained with an update panel.
C#
protected void CategorySelected_Click(object sender, EventArgs e)
{
//DB query to get items omitted
Button btn = (sender as Button);
string categoryid = btn.Attributes["data-categoryid"].ToString();
for (int i = 0; i < items.Rows.Count; i++)
{
if (items.Rows[i]["Category"].ToString() == categoryid)
{
Button ibtn = new Button();
ibtn.Click += new System.EventHandler(this.ItemSelected_Click);
ibtn.Attributes["runat"] = "server";
ibtn.ID = "ItmSelBtn" + i;
ibtn.Attributes["data-itemid"] = qry.GetItems().Rows[i]["id"].ToString();
//And again some none relevant attributes here
ItemsParent.Controls.Add(ibtn);
}
}
ItemsPanel.Update();
}
ASP
<div class="col-md-2 items-pane">
<asp:UpdatePanel ID="ItemsPanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="False">
<ContentTemplate>
<div id="ItemsParent" runat="server">
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
<div class="col-md-8 view-pane">
<asp:UpdatePanel ID="ItemDetailsPanel" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="False">
<ContentTemplate>
<div id="ItemDetailsParent" runat="server">
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
Again this generates a list of buttons for each item matching the correct category. No issue there, but this time I need the clicked button to call the third and final method which will display the details for the item. This is where things stop working. I assumed that because I was able to generate buttons successfully on Page_Load() that it would work the same inside an update panel. Right now the third method just contains a debug line to check if its firing at all.
protected void ItemSelected_Click(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("Item has been selected");
ItemDetailsPanel.Update();
}
In my output console in visual studio when I click on an Item Button control it writes Page Loaded indicating a successful postback but I am not seeing Item has been selected indicating that the third method is firing. I also inserted a breakpoint there but it is not being reached.
I initially thought I needed to add an asyncpostback trigger for each button generated to my update panel but that did not seem to resolve that issue, and because I can now see that Page_Load() is getting triggered I am pretty sure that isn't the issue. This leads me to believe that the click event is somehow not being registered. So my question to you is this: How do I make a dynamically generated button inside an update panel call a server side method? Any help is greatly appreciated.
You need to attach the event handlers on every postback.
It works for your categories-buttons, because the attaching is executed on every page load.
Do this for all the other items also, e.g. put in your Page_Load something like this:
foreach (var ctrl in ItemsParent.Controls)
{
Button ibtn = ctrl as Button;
if (ibtn != null)
{
ibtn.Click += new System.EventHandler(this.ItemSelected_Click);
}
}

Handling events for dynamically generated .NET user control

I am working on a page that accepts scanned input into a textbox. Once input is entered into the textbox, a user control that contains additional fields for the input item is dynamically generated via autopostback. The user control also contains a link button that is intended to delete the item (itself). Clicking this button generates a "delete" event that is supposed to bubble up to the parent.
Unfortunately this does not seem to happen - the deletion handling code is never reached. My understanding is that it is because the controls have not been generated yet at page load, so the event handlers have not been created yet. But since I don't know what controls need to be generated at page load (since the user input hasn't been processed yet), I can't move the code to generate the user controls to PageLoad.
How should this be handled? Am I going about this the wrong way? Most of my relevant code is below.
Thanks for any help!
page.aspx:
Enter SKU (tab to enter):
<asp:TextBox ID="EntryTextBox" CssClass="textbox" AutoPostBack="true" OnTextChanged="newItem" runat="server"></asp:TextBox>
<asp:Panel ID="itempanel" runat="server">
</asp:Panel>
page.aspx.cs:
protected void newItem(object sender, EventArgs e)
{
// we need to store item entries in ViewState so they comeback on postback;
// they can't be stored in the controls themselves as the controls will
// disappear
ViewState["skus"] += "\t" + EntryTextBox.Text;
ViewState["descs"] += "\t" + itemLookup(EntryTextBox.Text);
// ...more item descriptors...
updateItemPanel();
}
protected void updateItemPanel()
{
// generate a control for each item entered in ViewState
itempanel.Controls.Clear();
List<string> skus = new List<string>(ViewState["items"].ToString().Substring(1).Split('\t'));
List<string> descs = new List<string>(ViewState["descs"].ToString().Substring(1).Split('\t'));
// ...more item descriptors...
int i = 0;
foreach (string sku in skus)
{
item newitemctrl = (item)Page.LoadControl("~/item.ascx");
newitemctrl.line = (i + 1).ToString();
newitemctrl.sku = skus[i];
newitemctrl.description = descs[i];
// ...more item descriptors...
newitemctrl.deleteLinkClicked += new EventHandler(deleteClicked);
itempanel.Controls.Add(newitemctrl);
i++;
}
}
protected void deleteClicked(object sender, EventArgs e)
{
List<string> skus = new List<string>(ViewState["skus"].ToString().Substring(1).Split('\t'));
List<string> descs = new List<string>(ViewState["descs"].ToString().Substring(1).Split('\t'));
// ...more item descriptors...
item olditemctrl = (item)sender;
skus.RemoveAt(Convert.ToInt32(olditemctrl.number) - 1);
descs.RemoveAt(Convert.ToInt32(olditemctrl.number) - 1);
ViewState["skus"] = skus.ToString();
ViewState["descs"] = descs.ToString();
updateItemPanel();
}
item.ascx:
<asp:LinkButton ID="DeleteLinkButton" runat="server" onclick="DeleteLinkButton_Click">Delete</asp:LinkButton>
item.ascx.cs:
public event EventHandler deleteLinkClicked;
protected void DeleteLinkButton_Click(object sender, EventArgs e)
{
if (this.deleteLinkClicked != null)
{
this.deleteLinkClicked(new object(), new EventArgs());
}
}
You can dispatch a postback event in javascript by adding this as onclick event:
__doPostBack("<%= button.ClientID %>", "");
DoPostBack has two arguments, the first is the ID, the second is the event name.
I used this solution successfully.
You'll find more information here.
Note:
This itself does not fire the event automatically, but you can see what you want to happen in the Load Event of your page.
You can get the arguments like this: : Request.Form["__EVENTTARGET"]
You have full access to the form data, so you can also get the values from the dynamically created controls

Hide button on drop down selection -1

I need my create button to be hidden unless a facility is selected in my dropdown. When it is at -1 message i need my button to be hidden.
Code for button
<asp:Button ID="btnCreate" runat="server" Text="Create New" Width="89px" Font-Size="X-Small" OnClick="btnCreate_Click" />
Drop down code
private void ResetForm()
{
try
{
//facility dropdown
ddlFacility2.Items.Clear();
ddlFacility2.DataSource = this.DataLayer.model.MS_spGetFacilityInfo(null).OrderBy(x => x.FacilityName);
ddlFacility2.DataTextField = "FacilityName";
ddlFacility2.DataValueField = "FacilityID";
ddlFacility2.DataBind();
ddlFacility2.Items.Insert(0, new ListItem("All Facility Records..", "-1"));
BindGrid();
}
catch (Exception ex)
{
this.SetMessage(ex.ToString(), PageMessageType.Error);
AISLogger.WriteException(ex);
}
}
in first time page load if the default value selected is -1 you can set your button visible false as default.
in your droupdown list selected index change event you can enable/dissable button based on droupdown list selected value.
Add a OnSelectedIndexChange event to your dropdown list or add a clientside event to your dropdownlist. Double Click on your ddl you will see a function named ddlFacility2_OnSelectedIndexChanged in you code behind and add the below code to it.
Add AutoPostBack=true to you ddl
protected void ddlFacility2_OnSelectedIndexChanged(object sender, EventArgs e)
{
if(ddlFacility2.SelectedIndex>-1)
{
btnCreate.Enabled = true;
}
else
{
btnCreate.Enabled = false;
}
}
You can wire up a JQuery script that can bind to your DropDownList's selected value...
In this example, the button's visibility is bound on a click from another button:
$('#Button1').bind("click", function() {
$("#Button2").hide();
});
I dont know the exact syntax to use for the binding to selected value, but the above code should be a good place to start.

page variable in a repeater

Hi I'm having a bit of an issue with a asp.net repeater
I'm building a categories carousel with the dynamic categories being output by a repeater.
Each item is a LinkButton control that passes an argument of the category id to the onItemClick handler.
a page variable is set by this handler to track what the selected category id is....
public String SelectedID
{
get
{
object o = this.ViewState["_SelectedID"];
if (o == null)
return "-1";
else
return (String)o;
}
set
{
this.ViewState["_SelectedID"] = value;
}
}
problem is that i cant seem to read this value while iterating through the repeater as follows...
<asp:Repeater ID="categoriesCarouselRepeater" runat="server"
onitemcommand="categoriesCarouselRepeater_ItemCommand">
<ItemTemplate>
<%#Convert.ToInt32(Eval("CategoryID")) == Convert.ToInt32(SelectedID) ? "<div class=\"selectedcategory\">":"<div>"%>
<asp:LinkButton ID="LinkButton1" CommandName="select_category" CommandArgument='<%#Eval("CategoryID")%>' runat="server"><img src="<%#Eval("imageSource")%>" alt="category" /><br />
</div>
</ItemTemplate>
</asp:Repeater>
calling <%=SelectedID%> in the item template works but when i try the following expression the value of SelectedID returns empty..
<%#Convert.ToInt32(Eval("CategoryID")) == Convert.ToInt32(SelectedID) ? "match" : "not a match"%>
the value is being set as follows...
protected void categoriesCarouselRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
SelectedID = e.CommandArgument.ToString();
}
Any ideas whats wrong here?
Within the categoriesCarouselRepeater_ItemCommand code you've shown, you're assigning the CommandArgument to a property called 'SelectedCategory'.
Should this not be assigning the property to the 'SelectedID' property instead?
** EDIT..
The problem I see is one of two scenarios:
1) You are not rebinding the repeater with each postback, and therefore the expression within your ItemTemplate is not being evaluated - The output from the repeater will remain unchanged with each postback.
OR
2) You are rebinding the repeater control with each postback, however, upon clicking on your LinkButton for the first time, the repeater control is re-binded PRIOR to the ItemCommand event handler firing, and therefore, the 'SelectedID' property has not been set until after the repeater has finished being output.
If you were to click on one of your LinkButtons a 2nd time, the previously selected ID would be in viewstate at the time of the repeater control contents being rendered, and therefore be one step behind in rendering which category has been clicked, and so on...

End user add values to a dropdownlist?

I'm populating a dropdownlist in c# asp.net-MVC from a SQL table using Linq2Sql. I'd like for the user to be able to enter something that isn't in the list into the drop down and have it add to the table. Is this possible?
Sounds like you need to add a radio button labeled "Other". When the user clicks the radio button a text box would appear that allows the user to input a new value that you can save to your DB and display in the drop down.
EDIT:
Quick snippet to enable the control using JavaScript:
<script language="javascript" type="text/javascript">
function radioclicked() {
textObj = document.getElementById('<NAME OF TEXT BOX');
textObj.disabled = false;
}
</script>
You can use a check box instead of a radio button so that the enabled property can be toggled.
To completely hide the text box then you will have to look into jQuery/Ajax.
Why can't we use a lightweight Add-on like www.combodropdown.info for this purpose? You can even consider AutoComplete plugin from jQuery, if your app already references jQuery.
Also a combobox will allow a user to enter a value in addition to picking from a list.
My MVC is not so so, but I assume this still applies as MVC is just model view controller.
What if you throw a drop down on your form visible=true, and a textbox on your form visible =false.
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
<asp:TextBox ID="TextBox1" runat="server" Visible="False"></asp:TextBox>
Fill your drop down:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<int> s = Enumerable.Range(1, 10).ToList();
DropDownList1.DataSource = s;
DropDownList1.DataBind();
DropDownList1.Items.Add("Other");
}
}
Add an event to handle if someone selects other. If they do make the textbox visible:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
switch (this.DropDownList1.SelectedItem.Text)
{
case "Other":
this.TextBox1.Visible=true;
break;
default:
this.TextBox1.Visible=false;
break;
}
}
Now you can enter your value and re-store back to the db.

Categories

Resources