ASP.NET MVC - Open Table in new window and print - c#

I'm using ASP.NET MVC and have a table with 9 columns which shows results from the database where the user can filter values based on columns. The table structure looks like this:
<table class="tableMain" id="x">
<thead>
<tr class="trMain">
<th class="thMain">
#Html.DisplayNameFor(model => model.ID)
</th>
<th class="thMain">
#Html.DisplayNameFor(model => model.YEAR)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr class="trMain">
<td class="tdMain">
#Html.DisplayFor(modelItem => item.ID)
</td>
<td class="tdMain">
#Html.DisplayFor(modelItem => item.YEAR)
</td>
<td class="tdMain">
<input type="checkbox" class="chkCheckBoxId" name="airlineId" value="#item.ID" />
</td>
<td class="tdMain">
#Html.ActionLink("EditValue", "Edit", new { id = item.ID })
</td>
</tr>
}
</tbody>
</table>
Now I need a button, so that the dynamically generated table opens in a new window and the print dialog opens automatically. I had this piece of code:
<div class="line-btn">
<input type="submit" value="print" onclick="printTable()" class="btn fl btn-print">
</div>
<script language="javascript">
function printTable()
{
var printContent = document.getElementById("x");
var windowUrl = 'about:blank';
var num;
var uniqueName = new Date();
var windowName = 'Print' + uniqueName.getTime();var printWindow = window.open(num, windowName, 'left=50000,top=50000,width=0,height=0');
printWindow.document.write(printContent.innerHTML);
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
}
</script>
The problem here is that the table is completely unsorted when printed so the rows/columns are shifted.
I found this example:
https://datatables.net/extensions/buttons/examples/print/simple.html
This is exactly what I need (open the table in a new window and open print dialog). But unfortunately this sample has a lot of code in the javascript files that I don't need. There is a search field included and a pagination.
Can someone help me please? Thank you very much!

Ok I found a good solution.
This is the code I used:
<script src="#Url.Content("~/Scripts/jquery-3.5.1.js")" type="text/javascript"></script>
<script>
var myApp;
myApp = (function (app) {
$('#x').click(function () {
myApp.print();
});
app.print = function () {
$.ajax({
url: 'Home/Print',
success: function (data) {
if (myApp.arePopupsBlocked()) {
alert('please allow popups.');
}
var printWindow = window.open();
if (printWindow) {
$(printWindow.document.body).html(data);
} else {
alert('please allow popups.');
}
},
error: function () {
alert('Error');
}
});
};
app.arePopupsBlocked = function () {
var aWindow = window.open(null, "", "width=1,height=1");
try {
aWindow.close();
return false;
} catch (e) {
return true;
}
};
return app;
})(window.myApp || {})
</script>
and right before the table-tag the link to click:
<style>
/* suppress link for printing */
##media only print {
a {
display: none;
}
}
</style>
[print table]
There opens no new window but the table is well formated for printing.

Related

Using jQuery to get multiple checkbox's value and Multiple Delete Using jquery json

I have already bind a html table using jQuery json.
I want to get multiple checkbox value using jQuery json and delete by selected multiple delete method.
This is my code for bind the table.
$(function () {
debugger
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebForm5.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function (dt) {
debugger;
for (var i = 0; i < dt.d.length; i++) {
$("#example1 > tbody").append("<tr><td> <input type='checkbox' /></td><td>" + dt.d[i].CategoryID + "</td><td>" + dt.d[i].Name + "</td><td>" + dt.d[i].Status + "</td><td> <button type='submit'>Submit</button><button type='submit' onclick='deleteRecord(" + dt.d[i].CategoryID + ")'>Delete</button> </tr>");
}
$("#example1").DataTable();
},
error: function (result) {
alert("Error");
}
});
});
This is my Button to Delete selected(multiple delete):
<button type="button" name="deletebtn" id="deletebtn">Delete Selected</button>
This is my html table:
<div class="box-body">
<button type="button" name="deletebtn" id="deletebtn">Delete Selected</button>
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Check Box</th>
<th>Category Name</th>
<th>Category Details</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody id="myBody">
</tbody>
</table>
</div>
You just tell me :
1.what is the code to select all the checkbox??
2.Code to delete using multiple jquery??
The Server side Code is here For Single Delete(with out checkbox):
[WebMethod]
public static void deleteRecord(int Id)
{
clsCategoryBL objproject = new clsCategoryBL();
objproject.CategoryDelete(Id);
}
In BL:
public string CategoryDelete(int CategoryID)
{
using (KSoftEntities db = new KSoftEntities())
{
try
{
var categoryDetails = db.tblCategories.Where(i => i.CategoryID == CategoryID).SingleOrDefault();
db.tblCategories.Remove(categoryDetails);
db.SaveChanges();
return "Record deleted successfully";
}
catch (Exception ex)
{
}
return "Error on deletion";
}
}
The Delete is Occur on the Client Side by Using This code:
$().ready(function () {
$('body').on('click', '#deletebtn', function () {
debugger;
$("#example1 tr").each(function () {
var rowSelector = $(this);
if (rowSelector.find("input[type='checkbox']").prop('checked')) {
rowSelector.remove();
}
});
});
});
The Code For Bind The Table:
enter code here
protected void Page_Load(object sender, EventArgs e)
{
if (Session["adminuser"] == null)
Response.Redirect("Default.aspx");
if (!IsPostBack)
{
// Page.Title = "Category Details";
BindDatatable();
}
}
[WebMethod]
public static UserDetails[] BindDatatable()
{
clsCategoryBL objcategory = new clsCategoryBL();
List<UserDetails> details = new List<UserDetails>();
DataTable dt = new DataTable();
//var categories= clsCategoryBL.GetAllCategoryDetails("admin");
dt = objcategory.GetAllCategoryDetails("admin");
if (dt.Rows.Count > 0)
{
foreach (DataRow dtrow in dt.Rows)
{
UserDetails user = new UserDetails();
user.CategoryID = dtrow["CategoryID"].ToString();
user.Name = dtrow["Name"].ToString();
user.Status = dtrow["Status"].ToString();
details.Add(user);
}
//literal1.Text = html.ToString();
}
return details.ToArray();
}
public class UserDetails
{
public string CategoryID { get; set; }
public string Name { get; set; }
public string Status { get; set; }
}
I want To delete it on server Side that means also on my database(Sql)
So what should i do???
I Want To Delete Multiple Row By Click On Multiple CheckBox On Database Also..I have mention in above the backend code also..I want to delete the row of html table by click 2 to 3 checkbox(it may be vary depend upon the data) and click Delete Selected button..
The Table structure after pressing f12:
enter code here
<table id="example1" class="table table-bordered table-striped dataTable no-footer" role="grid" aria-describedby="example1_info">
<thead>
<tr role="row"><th class="sorting_asc" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Check Box: activate to sort column descending" style="width: 204px;">Check Box</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Category Name: activate to sort column ascending" style="width: 276px;">Category Name</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Category Details: activate to sort column ascending" style="width: 293px;">Category Details</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Status: activate to sort column ascending" style="width: 148px;">Status</th><th class="sorting" tabindex="0" aria-controls="example1" rowspan="1" colspan="1" aria-label="Action: activate to sort column ascending" style="width: 211px;">Action</th></tr>
</thead>
<tbody id="myBody">
<tr role="row" class="odd"><td class="sorting_1"> <input type="checkbox"></td><td>42</td><td>xyz</td><td>True</td><td> <button type="submit">Submit</button><button type="submit" onclick="deleteRecord(42)">Delete</button> </td></tr><tr role="row" class="even"><td class="sorting_1"> <input type="checkbox"></td><td>33</td><td>Advertising</td><td>True</td><td> <button type="submit">Submit</button><button type="submit" onclick="deleteRecord(33)">Delete</button> </td></tr><tr role="row" class="odd"><td class="sorting_1"> <input type="checkbox"></td><td>31</td><td>Travel & Hospitality</td><td>True</td><td> <button type="submit">Submit</button><button type="submit" onclick="deleteRecord(31)">Delete</button> </td></tr></tbody>
</table>
Assuming there is only one checkbox in a row, you could simply iterate through the rows and post to your existing [WebMethod]
Using the second column as the ID (EDIT):
$().ready(function () {
$('body').on('click', '#deletebtn', function () {
$("#example1 tr").each(function () {
var rowSelector = $(this);
if (rowSelector.find("input[type='checkbox']").prop('checked'))
{
//THE MARKUP SHOWING THE ID IS NOT AVAILABLE
//POST A TABLE ENTRY TO CLEAR UP
var id = rowSelector.find('td').first().next().html();
var sendObj = {Id : id};
//USE JSON OBJECT
$.ajax({
url : "/page.aspx/deleteRecord",//CHANGE TO YOUR URL
dataType: "json",
data: sendObj,
type: "POST",
success: function () {
alert("entry deleted");
}
});
rowSelector.remove();
}
});
});
});
Explanation
Using JQuery you simply iterate through each row and look for the checkbox value. Note you will iterate through the header as well, so if there is a checkbox there you must add logic to skip the first iteration.
EDIT 3: You will also post the ID to the server if the checkbox is checked. Important to note that you would rather post a single bulk array of ID's instead of multiple single posts, but that method has not been exposed or posted here.
Good Luck
CODE SNIPPET (CLIENT SIDE ONLY)
$().ready(function () {
$('body').on('click', '#deletebtn', function () {
$("#example1 tr").each(function () {
var rowSelector = $(this);
if (rowSelector.find("input[type='checkbox']").prop('checked'))
{
rowSelector.remove();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id='deletebtn'>DELETE</button>
<table id='example1'>
<thead>
<tr>
<th>CHECKBOX</th>
<th>NAME</th>
<th>DESCRIPTION</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type='checkbox' value='check' /></td>
<td>the name</td>
<td>the description</td>
</tr>
<tr>
<td><input type='checkbox' value='check' /></td>
<td>the name</td>
<td>the description</td>
</tr>
<tr>
<td><input type='checkbox' value='check' /></td>
<td>the name</td>
<td>the description</td>
</tr>
</tbody>
</table>
</div>
A easier method will be if you give a class to all the check-boxes in your form and then on button click you simply iterate through all the check-boxes using the class, and therby seralizing their values.
var values = $("#Myform").find(".CheckBoxClass").serialize();
here the variable value will contain the values of all the checkboxes in your form and you can send them using ajax on your server to perform further action.
You can use something like below mentioned.
$("example1 input:checkbox").prop('checked',this.checked);
Or it is answered already in below post
jquery set all checkbox checked

jQuery AJAX, conditional not working

My function makes a search by ID and by name, and I'm doing it in MVC. The problem is that it enters the conditional (if) and the AJAX is run correctly, but then it also goes to the else and runs it too. Apparently my data in the dialog is blank because it send the alert window. It sometimes opens the dialog correctly, but when I change the module and come back the if and else are run again and the blank dialog appears.
What can be happening? When I make the first click, it blocks, I click again and then the data appears...
function buscaProducto(url, cod, name) {
if (cod.length != 0 || name.length != 0) {
var producto = name;
var identidad = cod;
$.ajax({
url: url,
type: "POST",
dataType: "html",
error: AjaxFailure,
beforeSend: AjaxBegin,
data: { productoNombre: producto, identidad: identidad },
success: function (data) {
$("#dialog").dialog({
bigframe: true,
modal: true,
autoOpen: true,
width: 900,
heigth: 700,
resizable: false,
});
$("#progressbar").hide();
$("#dialog").html(data);
console.log("Entregó los datos al #dialog");
}
});
}
else {
alert("<p>Debe ingresar una opcion de busqueda</p>", $(window).height() / 3)
this.abort();
}
}
I think the cache might be stuck
the controller
[HttpPost]
public ActionResult BusquedaProducto(string productoNombre, string identidad)
{
if (productoNombre.Equals(""))
{
if (identidad.Equals(""))
{
return HttpNotFound();
}
else
{
var code = (from p in db.GN_Portafolio
where p.CodigoPortafolio.StartsWith(identidad) && p.SenSerial == true
select p).ToList();
if (code.Equals("0"))
{
return HttpNotFound();
}
else
{
return View(code);
}
}
}
else
{
var producto = (from p in db.GN_Portafolio
where p.NombrePortafolio.StartsWith(productoNombre)
select p).ToList().Take(100);
if (producto.Equals("0"))
{
return HttpNotFound();
}
else
{
return View(producto);
}
}
}
the view
#model IEnumerable<SifActivoFijo.Models.GN_Portafolio>
<form class="items">
<label>items por Pagina: </label>
<select>
<option>5</option>
<option>10</option>
<option>15</option>
</select>
</form>
<input name="button" type="button" onclick="$('#dialog').dialog('close');" value="Cerrar" />
<table class="tablas">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.CodigoPortafolio)
</th>
<th>
#Html.DisplayNameFor(model => model.NombrePortafolio)
</th>
<th></th>
</tr>
</thead>
<tbody id="pagina">
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CodigoPortafolio)
</td>
<td>
#Html.DisplayFor(modelItem => item.NombrePortafolio)
</td>
<td>
<input class="seleccion" type="button" value="Seleccionar" />
</td>
</tr>
}
</tbody>
</table>
<div class="holder"></div>
<script type="text/javascript">
$(document).ready(function () {
$('input.seleccion').click(function () {
var codigo = $(this).parent().prev().prev();
var nombre = $(this).parent().prev();
$('#activoFijo_GN_Portafolio_CodigoPortafolio').val($.trim(codigo.text()));
$('#GN_Portafolio_CodigoPortafolio').val($.trim(codigo.text()));
$('#nombrePortafolio').val($.trim(nombre.text()));
$("#activoFijo_DescripcionActivoFijo").val($.trim(nombre.text()));
document.getElementById("dialog").innerHTML = '<div id="progressbar" class="progressbar" style="display: none;"></div>';
$("#dialog").dialog('close');
});
});
You are using return type as ActionResult in server side method. So this return your entire view, then page will get reload. So this has happening. So please change your methods return type to any other like string, Jsonresult, etc.,  

Checkbox (model) dosn't change value when checked

Ive made some checkboxes in a View. The checkboxes is implemented via the ViewModel with bool properties. I'm currently trying to change a query in the controller to "date" or "month" depending if the checkbox has been checked. However in the Controller it always jumps the the "else statement" even if "Month" has been checked. Month is always False.
I suspect the JavaScript code might be wrong.
This User Interface:
In my Controller method i try to do the following:
Controller:
var request = GoogleAnalyticsService.Data.Ga.Get("ga:59380223", start, end, "ga:visitors");
var request = GoogleAnalyticsService.Data.Ga.Get("ga:59380223", start, end, "ga:visitors");
if (model.Month)
{
request.Dimensions = "ga:month";
request.Sort = "-ga:month";
}
else
{
request.Dimensions = "ga:date";
request.Sort = "-ga:date";
}
request.MaxResults = 10000;
Google.Apis.Analytics.v3.Data.GaData d = request.Execute();
In The view ive implemented my Viewmodel and tried writing some javascript checking if what checkbox have ´been checked and if to return true or false:
View:
<table class="adminContent">
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.StartDate):
</td>
<td class="adminData">
#Html.EditorFor(model => model.StartDate)
</td>
</tr>
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.EndDate):
</td>
<td class="adminData">
#Html.EditorFor(model => model.EndDate)
</td>
</tr>
<tr>
<td class="data" colspan="2">
#Html.CheckBoxFor(model => model.Date, new { id = "Day" }) // -- Checkbox Date
#Html.LabelFor(model => model.Date)
</td>
</tr>
<tr>
<tr>
<td class="data" colspan="2">
#Html.CheckBox("chkMonth", new { #onclick = "updatemyhidden(this)" }) // -- Checkbox Month
#Html.HiddenFor(model => model.Month, new { id = "Month" })
#Html.LabelFor(model => model.Month)
</td>
</tr>
</tr>
<tr>
<td class="adminTitle">
#Html.NopLabelFor(model => model.GAStatisticsId ):
</td>
<td class="adminData">
#Html.DropDownList("GAStatisticsId", Model.AvailableGAStatistics)
<input type="button" id="GAStatisticsReport-Submit" class="t-button" value="#T("Admin.Common.Search")" />
</tr>
</table>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="/Scripts/jquery.min.js"></script>
<script type="text/javascript">
$("#GAStatisticsReport-Submit").click(function () {
if ($("select[name='GAStatisticsId'] option:selected").text() == "Visitors Report")
drawChartVisitors()
if ($("select[name='GAStatisticsId'] option:selected").text() == "Orders Report")
drawChartOrders()
if ($("select[name='GAStatisticsId'] option:selected").text() == "Conversion Report")
drawConversion()
function updatemyhidden(chkbox) {
$("#Month").val(chkbox.checked);
}
})
google.load("visualization", "1", { packages: ["corechart"] });
google.load("visualization", "1", { packages: ["treemap"] });
function drawChartVisitors() {
$.get('/GAStatistics/GetVisitors', {
StartDate: $('##Html.FieldIdFor(model => model.StartDate)').val(),
EndDate: $('##Html.FieldIdFor(model => model.EndDate)').val(),
},
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('date', 'Date');
tdata.addColumn('number', 'Visitors');
for (var i = 0; i < data.length; i++) {
if ($("#Month").is(":checked")) {
var dateStr = data[i].Date.substr(0, 4);
}
else {
var dateStr = data[i].Date.substr(0, 4) + "-" + data[i].Date.substr(4, 2) + "-" + data[i].Date.substr(6, 2);
}
tdata.addRow([new Date(dateStr), parseInt(data[i].Visitors)]);
}
The if-statements in the controller dosnt seem to operate depending on what i select in the view.
Note: im not using httpPost/get as the data is loaded with Google Charts and i don't want the whole page to re-aload each time a new request is selected.
Is because you set bool field on the month so it will rendered as true/false for your checkbox. You have a look at the rendered HTML for the month checkbox., and no matter you checked or not the data still send back to server as true/false depend what been set when rendering the page. This value will never change.
So i suggest you either add one more property in your viewmodel to keep try check/unchecked state and in the view rendered it as hidden field and update this hidden field whenever checkbox is ticked/unticked.
Or the month field render as hidden field and add one more checkbox in the page to update the month field when checkbox is checked/unchecked
Let say we use 2nd approach, the code will look something like this, (I did not test the code below). I hope this helps:
#Html.CheckBox("chkMonth", new { #onclick = "updatemyhidden(this)" })
#Html.HiddenFor(model => model.Month)
<script type="text/javascript">
function updatemyhidden(chkbox) {
$("#Month").val(chkbox.checked);
}
</script>

Jquery ui Dialog in an MVC listing table

I have a listing table displaying some information from the database.
What i am trying to do is to check if the item status is 1 and if comments exists to display a little icon where the user will click on it and see the specific comment for that item.
So in the listing table it seems to display fine that icon according to the above criteria but when i click on a specific listing it opens all dialogs with comments for all other listings with the same item status instead of the one i have chosen.
Can you please help me on what am i doing wrong ?
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.BookingId)
</td>
<td>
<a href="#Url.Action("ItemDetails", new {id=item.ItemId })" title="#item.Item.ItemDescription">
#Html.DisplayFor(modelItem => item.Item.ItemName)
</a>
</td>
<td>
#Html.DisplayFor(modelItem => item.StartDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.EndDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.RequestDate)
</td>
#if (item.StatusCodeId == 1)
{
<td style="color:#DD7500">
#Html.DisplayFor(modelItem => item.StatusCode.StatusCodeName)
#if (item.Comments != null)
{
<img class="orangeclicker" style="margin-left:3px;display:inline;margin-bottom:-3px;cursor: pointer;" title="Tutor Comments" src="~/Images/chat_icon.gif" />
<div class="orangedialog" title="Tutor Comments">
<p> #item.Comments</p>
</div>
}
</td>
}
}
</tr>
}
</table>
<script> $(function ()
{
$(" .orangedialog").dialog({
autoOpen: false,
show: { effect: "blind", duration: 1000 },
hide: { effect: "explode", duration: 1000 },
buttons: {
Close: function () {
$(this).dialog("close");
}
}
});
$('.orangeclicker').live("click", function () {
$(".orangedialog").dialog("open");
});
});
</script>
You should try this:
first;you have to create links in each row of table having same class.
<a class="comments">Comments</a>
second; update your page as:
<div id="dialog-details" style="display: none">
<p>
#if (item.Comments != null)
{
<img class="orangeclicker" style="margin-left:3px;display:inline;margin-bottom:-3px;cursor: pointer;" title="Tutor Comments" src="~/Images/chat_icon.gif" />
<div class="orangedialog" title="Tutor Comments">
<p> #item.Comments</p>
</div>
}
</p>
</div>
third update your script as:
$('.comments').click(function () {
$("#dialog-details").dialog('open');
return false;
});
$("#dialog-details").dialog({
autoOpen: false,
resizable: false,
height: 170,
width: 350,
show: { effect: 'drop', direction: "up" },
modal: true,
draggable: true,
open: function (event, ui) {
$(".ui-dialog-titlebar-close").hide();
},
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
</script>
They all have the same id or class ( because they are render in a foreach statement )
You can add a difference by combining the class or the id with the index from your list
I don't have the code in front of me, but I also think something like this would work.
UPDATE:
$('.orangeclicker').live("click", function (e) {
alert("check"); // if this fires at click, the problem is somewhere else
var target= $(e.currentTarget);
target.next().dialog("open");
});
You should Use $(this).next().next().find(".orangedialog") to find relevent element.
$('.orangeclicker').on("click", function (e) {
$element = $(this).next().next().find(".orangedialog");
$element.dialog("open");
});
Update
Use on() instead of live()
See DEMO

JavaScript How Can I achive this in delete dialog

OK So I have view with data in table and i made delete option like in this tutorial
http://ricardocovo.com/2010/09/02/asp-mvc-delete-confirmation-with-ajax-jquery-ui-dialog/
But Now I have a question How Can I get a Name from the correct line to write something like this
Do you really want to delete "Product Name"
I think he asked about ASP.NET MVC, not Web forms, so the code will be as below
The view will be
<table id="table">
<tr>
<td>Id</td>
<td>Name</td>
<td> </td>
</tr>
#foreach(var item in Mode.Items) {
<tr>
<td>#item.Id</td>
<td>#item.Name</td>
<td><button class="deleted-link" value="Delete">delete</button></td>
</tr>
}
</table>
<div id="delete-dialog" title="Confirmation">
</div>
and the Jquery script on the view should be
$(function(){
//alert($('.deleted-link'));
$('.deleted-link').each(function(){
$(this).click(function(data){
var id = $(this).parent().parent().find('td :first').html();
$('#delete-dialog').html('<p>Are you sure you want to delete the item with id = {' + id + '} ?</p>');
$('#delete-dialog').dialog('open');
});
});
$('#delete-dialog').dialog({
autoOpen: false, width: 400, resizable: false, modal: true, //Dialog options
buttons: {
"Continue": function () {
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
});
You can see the code example at http://jsfiddle.net/SVgEL/
Hope this help.
You can try some thing Like this
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
ImageButton imb = (ImageButton)e.Row.FindControl("deleteButton");
string recordName = e.Row.Cells[3].Text;
imb.OnClientClick = "return confirm('Are You sure Want to Delete the record:- "+ recordName.ToUpper()+" ? ');";
}
}
Normal click Event with button
Delete
What about passing the model to the view and displaying the name?
Cant add comments, sorry for posting here in answers space.
If you dont want to pass the model you can always just pass the name as a parameter to the delete function from the table view.
Assuming that you are already using jQuery, check this out:
<script type="text/javascript">
function removeCar(theLink) {
var theTR = $(theLink).parents('tr');
var model = $(theTR).children('td._model').html();
var theConfirm = confirm("Are you sure you want to remove " + model + "?");
if (theConfirm == true)
$(theTR).remove();
}
</script>
<table>
<thead>
<tr>
<th>Make</th>
<th>Model</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Audi</td>
<td class="_model">A3</td>
<td>Remove</td>
</tr>
<tr>
<td>Audi</td>
<td class="_model">A4</td>
<td>Remove</td>
</tr>
<tr>
<td>Audi</td>
<td class="_model">A5</td>
<td>Remove</td>
</tr>
</tbody>
</table>

Categories

Resources