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();"andclass="deleteable-item"