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>
Related
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.
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
i have page view list like
#foreach (var item in Model)
{
<tr>
<td class="colcode">
#Html.DisplayFor(modelItem => item.SMCode)
</td>
<td class="colname">
#Html.DisplayFor(modelItem => item.Name)
</td>
<td class="colip">
#Html.DisplayFor(modelItem => item.IP)
</td>
<td class="coloffsetfund">
<div>
<span id="#item.IP.Replace(".","")"></span>
</div>
<div>
<span id="#item.SMCode"></span>
</div>
<script type="text/javascript">
$(document).ready(function () {
idtimer = '##item.IP.Replace(".","")';
password = '#item.Password';
ip = '#item.IP';
smcode = '#item.SMCode';
startTimer(idtimer);
$(idtimer).backward_timer({
seconds: '#item.DelaySecond',
on_exhausted: function (timer) {
alert('stop timer:' + idtimer);
//ajax call to update value
}
});
});
</script>
My list have 2 items but i dont know why. when event on_exhausted of timer excute, it always is the last item. i dont know what is logic here.How do I alert correct idtimer. thanks for your help!!!
sry guys,
i knew where is my problem, because i use variable to assign value, and when generated HTML, the variable always contain lastest value. i fixed it when use direct call like
$('##item.IP.Replace(".","")').backward_timer({
for other guy get problem same me :)
thank you.
In the past I've used jQuery/Ajax to capture the key press of an end user, and build up a WHERE clause to filter data on a Web form.
I'm now taking advantage of the strongly type facilitates in ASP.NET 4.5. I was wondering if anyone has a way of performing real-time filtering/searching on a Gridview.
Basically, I have three grids, all showing different information. I want the end-user to key in or select from a drop down list (generic searching) and all girds reflect those changes.
I'm not adverse to resorting back to the old method, just didn't; know if there was anything new I could use?
So you can look at this. I hope this help you.
Here is the HTML:
<input id="searchInput" value="Type To Filter">
<br/>
<table>
<thead>
<tr>
<th>Column1</th>
<th>Column2</th>
</tr>
</thead>
<tbody id="fbody">
<tr>
<td>cat</td>
<td>one</td>
</tr>
<tr>
<td>dog</td>
<td>two</td>
</tr>
<tr>
<td>cat</td>
<td>three</td>
</tr>
<tr>
<td>moose</td>
<td>four</td>
</tr>
<tr>
<td>mouse</td>
<td>five</td>
</tr>
<tr>
<td>dog</td>
<td>six</td>
</tr>
</tbody>
</table>
And here is the JavaScript code:
$("#searchInput").keyup(function () {
// Split the current value of searchInput
var data = this.value.split(" ");
// Create a jQuery object of the rows
var jo = $("#fbody").find("tr");
if (this.value == "") {
jo.show();
return;
}
// Hide all the rows
jo.hide();
// Recusively filter the jquery object to get results.
jo.filter(function (i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
return true;
}
}
return false;
})
// Show the rows that match.
.show();
}).focus(function () {
this.value = "";
$(this).css({
"color": "black"
});
$(this).unbind('focus');
}).css({
"color": "#C0C0C0"
});
Enter link description here
I have a small problem.
My action is :
public ViewResult SearchForRooms(int HotelDDL)
{
List<Room> roomsInHotel = bl.ReturnRoomsPerHotel(HotelDDL);
return View(roomsInHotel);
}
Here is the jquery that is calling the action:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#HotelDDL").change(function () {
var text = $("#HotelDDL option:selected").text();
var value = $("#HotelDDL option:selected").val();
alert("Selected text=" + text + " Selected value= " + value);
$.post("/Home/SearchForRooms",
{
HotelDDL: $("#HotelDDL option:selected").val()
});
});
});
</script>
And finally, here is the View that should be called:
#model IEnumerable<RoomReservation.Entities.Entities.Room>
#{
ViewBag.Title = "Search";
}
<h2>Result</h2>
<table>
<tr>
<th>
City
</th>
<th>
Hotel
</th>
<th>
Room label
</th>
<th>
Number of beds
</th>
<th>
Price per night
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelitem=>item.Hotel.City.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Hotel.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.NumberOfBeds)
</td>
<td>
#Html.DisplayFor(modelItem => item.PricePerNight)
</td>
</tr>
}
</table>
Everthing is working ok (databse return all rooms correctly) except final view rendering.
I have tried Phil's tool but it doesn't give me any suspicious hints:
RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
So, why is it not showing after jscript send it's post method to SearchForRooms()?
Thank you
P.S. If you need any other piece of code please just say so.
Note that doing an ajax post will not refresh or redirect the page like a classic post would.
The view is not showing because there is no where to place it. You post successfully, and return a view successfully but then do nothing with it. If you want to show the returned view, then you have to append it to the dom somehow. Here is a common method:
<div id="successDiv"></div>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$("#HotelDDL").change(function () {
var text = $("#HotelDDL option:selected").text();
var value = $("#HotelDDL option:selected").val();
alert("Selected text=" + text + " Selected value= " + value);
$.post("/Home/SearchForRooms",
{
HotelDDL: $("#HotelDDL option:selected").val()
}, function(result){//add callback for success - result is the returned view
$("#successDiv").html(result);//place the view inside of the div
});
});
});
</script>
Comment Response
#TunAntun - You should use a classic post if you want the view to have its own page. There is no way to accomplish this from ajax. You could do this with javascript though
$.post("/Home/SearchForRooms",
{
HotelDDL: $("#HotelDDL option:selected").val()
}, function(result){//add callback for success - result is the returned view
$("#successDiv").html(result);//place the view inside of the div
});
would become
var postForm = document.createElement("form");
postForm.setAttribute("method","post");
postForm.setAttribute("action","/Home/SearchForRooms");
var postVal = document.createElement("input");
postVal.setAttribute("type","hidden");
postVal.setAttribute("name","HotelDDL");
postVal.setAttribute("value",$("#HotelDDL option:selected").val() );
postForm.appendChild(postVal);
document.body.appendChild(postForm);
$(postForm).submit();
This will dynamically issue the post you wanted. Then in your controller it will properly redirect or return a view. It is highly suggested that when returning a view from a [HttpPost] that you use RedirectToAction and then return the view from a [HttpGet] method in order to prevent refresh from reposting old data.