On clicking the retire user checkbox I am triggering the form submit for ("RetireUser", "Users")
My script is navigating to /Users/RetireUser but I need to pass the Id parameter.
Didn't have much luck with ajax
Thanks in advance for the help
#foreach (var item in UsersModel)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.Username)</td>
<td>#Html.DisplayFor(modelItem => item.FirstName)</td>
<td>#Html.DisplayFor(modelItem => item.LastName)</td>
<td>#Html.DisplayFor(modelItem => item.Email)</td>
<td>#Html.DisplayFor(modelItem => item.Phone)</td>
<td>#Html.DisplayFor(modelItem => item.Status)</td>
<td>#Html.DisplayFor(modelItem => item.DateRetired)</td>
<td>#Html.DisplayFor(modelItem => item.DateAdded)</td>
#using (Html.BeginForm("RetireUser", "Users", FormMethod.Post, new { role = "form", id="retire_user" }))
{
<td>#Html.CheckBoxFor(modelItem => item.RetireUser)</td>
}
<td>Edit</td>
</tr>
}
<script>
$('#item_RetireUser').click(function () {
$('#retire_user').submit();
});
the html
the script
if it's a html why not give each a id i.e here 12 is user_id and with the help of jquery you can retrieve and send that id via ajax or normal url call.
Related
I am working on a Table Row filtering script.
Initially, the all table rows are visible, but after manipulating some dropdowns / forms the filter criteria dictate which rows are going to be visible and which not. Example:
var jobs = [{
id: 0,
company: "Google",
location: "Zurich"
}, {
id: 1,
company: "Facebook",
location: "Ireland"
}];
// this function isn't run in this example for reasons of brevity. it's to show how the jobs array is generated
const filterRow = function (data, filters) {
let filtersEnabled = Object.keys(filters).filter(element => filters[element].length !== 0);
return data.filter(row => {
return filtersEnabled.every(k => {
return filters[k].indexOf(row[k]) !== -1
})
})
}
let $tableRows = $('table tbody tr');
const updateDisplay = function() {
// that's not ideal
$tableRows.addClass('hidden')
jobs.forEach((row) => {
$(`[data-id="${row.id}"]`).removeClass('hidden')
})
}
$('.js-filter').on('click', () => updateDisplay())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<button class="js-filter">filter table now</button>
<table class="table table-bordered">
<tbody>
<tr data-company="google" data-id="0" data-loation="zurich">
<td>Google</td>
<td>Zurich</td>
<td>0</td>
</tr>
<tr data-company="facebook" data-id="1" data-loation="ireland">
<td>Facebook</td>
<td>Ireland</td>
<td>1</td>
</tr>
<tr data-company="microsoft" data-id="2" data-loation="california">
<td>microsoft</td>
<td>California</td>
<td>2</td>
</tr>
</tbody>
</table>
The jobs array determines which rows are going to be visible. (so in this particular case, only rows with id 0 and 1 are going to be visible.
Given that the jobs array is changing programmatically, I would like a jQuery (or other) way to directly hide the rows with ID not present in the array (thus being able to use animate.css to fade rows out etc.
What I currently do is
hiding all rows,
then showing the ones in the array. That's rather a workaround and it complicates my transitions/animations.
You can use the jQuery .filter() method to iterate over the rows and filter them.
On each iteration you can check to see if the row's data-id attribute is found in the jobs array by using the .some() method. From there, you can return the boolean and filter out rows that have an id that matches an object in the jobs array.
$rows.filter((index, row) => {
return !jobs.some(job => job.id === +row.dataset.id);
}).addClass('hidden');
Alternatively, you could also use the jQuery .not() method in place of .filter():
$rows.not((index, row) => {
return jobs.some(job => job.id === +row.dataset.id);
}).addClass('hidden');
Or if you want to break isJobById into another function:
const isJobById = id => jobs.some(job => job.id === +id);
const updateDisplay = () => {
$rows.not((i, row) => isJobById(row.dataset.id)).addClass('hidden');
}
You can also change the following line:
$('.js-filter').on('click', () => updateDisplay());
.. and pass the updateDisplay function directly:
$('.js-filter').on('click', updateDisplay);
Full snippet:
var jobs = [{
id: 0,
company: "Google",
location: "Zurich"
}, {
id: 1,
company: "Facebook",
location: "Ireland"
}];
let $rows = $('table tbody tr');
const isJobById = id => jobs.some(job => job.id === +id);
const updateDisplay = () => {
$rows.not((i, row) => isJobById(row.dataset.id)).addClass('hidden');
}
$('.js-filter').on('click', updateDisplay);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<button class="js-filter">filter table now</button>
<table class="table table-bordered">
<tbody>
<tr data-company="google" data-id="0" data-loation="zurich">
<td>Google</td>
<td>Zurich</td>
<td>0</td>
</tr>
<tr data-company="facebook" data-id="1" data-loation="ireland">
<td>Facebook</td>
<td>Ireland</td>
<td>1</td>
</tr>
<tr data-company="microsoft" data-id="2" data-loation="california">
<td>microsoft</td>
<td>California</td>
<td>2</td>
</tr>
</tbody>
</table>
Does Id have to be an integer or it can be string?
It seems like in my case #=INVOICE# is getting value but it Read method to controller not sure why not getting called.
I tried looking at this example: http://demos.telerik.com/kendo-ui/grid/detailtemplate
code:
#(Html.Kendo().Grid<OpenInvoicesInfo>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.INVOICE).ClientTemplate("<input type='checkbox' value='#= INVOICE #' class='testclass' />").Width(4);
columns.Bound(i => i.INVOICE).Width(15);
...
})
.ClientDetailTemplateId("OrdersTemplate")
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(8)
.Read(read => read.Action("GetOpenInvoices", "Maint", new { cust = Request.QueryString["cust"] }))
)
)
<script id="OrdersTemplate" type="text/kendo-tmpl">
#(Html.Kendo().Grid<CustomerComments>()
.Name("grid_#=INVOICE#")
.Columns(columns =>
{
columns.Bound(o => o.INVOICE).Width(15);
columns.Bound(o => o.Comment).Width(40);
})
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(10)
.Read(read => read.Action("GetCustomerComments", "Maint", new { invoices = "#=INVOICE#" }))
)
.Pageable()
.Sortable()
.ToClientTemplate()
)
Controller:
public ActionResult GetCustomerComments([DataSourceRequest] DataSourceRequest request, string invoices)
{
List<JNI.Enterprise.Contracts.CustomerComments> customer = InvoiceService.GetCustomerComments(invoices);
return Json(customer.ToDataSourceResult(request));
}
I will really appreciate if someone can reply.
Does it only work if it is in entity framework.
I am calling GetCustomerComments from a stored procedure.
It is loading the first grid fine but not calling details grid's controller method.
I'm trying to push an ajax response array into MVC table. This is how my script looks like:
<script type="text/javascript">
$(document).ready(function () {
$('#form1').submit(function (event) {
event.preventDefault();
event.returnValue = false;
var selectValue = $('#selectValue').val();
$.ajax({
url: "/api/Admin/GetDepotDetails/",
type: "POST",
data: { "selectValue": selectValue },
dataType: "json",
success: function (data) {
$("#Grid").html($(data).children());
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
alert(textStatus, errorThrown, jqXHR);
}
});
});
});
</script>
This is how my partial view looks like:
#model IEnumerable<SampleApp.DepotDetail>
<table class="table table-condensed" id="Grid">
<tr>
<th>
#Html.DisplayNameFor(model => model.DepotID)
</th>
<th>
#Html.DisplayNameFor(model => model.ColumnName)
</th>
<th>
#Html.DisplayNameFor(model => model.Country)
</th>
<th>
#Html.DisplayNameFor(model => model.CountryCode)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr class="warning">
<td>
#Html.DisplayFor(modelItem => item.DepotID)
</td>
<td>
#Html.DisplayFor(modelItem => item.ColumnName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Country)
</td>
<td>
#Html.DisplayFor(modelItem => item.CountryCode)
</td>
</tr>
}
</table>
This is how the WebApi method looks like:
[HttpPost]
public IEnumerable<DepotDetail> GetDepotDetails(Selected selectValue)
{
var model = depotsDetails.Where(x => x.ColumnName == selectValue.SelectValue) as IEnumerable<DepotDetail>;
var viewModel = new SearchViewModel{ DepotDetailsList = model, ActionLists = new ActionList()} ;
return model;
}
This is how the View looks like:
#model IEnumerable<SiemensSampleApp.DepotDetail>
<div class="row">
<div class="col-md-4">
<form id="form1">
#*#Html.DropDownListFor(model => model.DepotListSelectValue, Model.DepotLists, new { #class = "form-control" })*#
#Html.DropDownList("selectValue", new List<SelectListItem>
{
new SelectListItem() {Text = "Depot ID", Value="Depot ID"},
new SelectListItem() {Text = "Depot Name", Value="Depot Name"},
new SelectListItem() {Text = "Address", Value="Address"}
}, new { #class = "selectValue", #id = "selectValue" })
#*//, new { #class = "chzn-select", #id = "chzn-select" }*#
<input type="submit" value="submit" />
</form>
<br /><br /><br />
<table id="records_table" style="width:100%;"></table>
<div id="tableHere">
#{
if (Model == null)
{
Html.RenderPartial("_SearchResult", new List<DepotDetail>() { });
}
}
</div>
</div>
</div>
Question: Through WebApi i'm trying to get a List of details and bind it to a MVC table. What is the best way to do this?
I have used
$("#Grid").html($(data).children());
To fill the Grid. But the table doesn't have any data. can someone please give me an idea how to fill the grid using above Partial view.
Thank you in advance!
Your web api endpoint return data ( in json format), not the HTML markup from your partial view. You have 2 options.
1) Create an mvc action method which gets the data and pass it to your partial view and return the partial view response and use that to update your UI
[HttpPost]
public IEnumerable<DepotDetail> GetDepotDetails(Selected selectValue)
{
var model = depotsDetails.Where(x => x.ColumnName == selectValue.SelectValue)
as IEnumerable<DepotDetail>;
return PartialView(model);
}
Now make sure you have a partial view called GetDepotDetails.cshtml in ~/Views/Shared or ~/View/YourControllerName/. This view should be strongly typed to a collecction of DepotDetail.
#model IEnumerable<DepotDetail>
<p>Here loop through each item in Model and render the table</p>
<p> Same as your partial view in the question </p>
And in your success event,
success: function (data) {
$("#Grid").html(data);
},
2) Use your current web api endpoint and read the data in your ajax method's success event and dynamically build the html markup for the table rows and set that as the content of your Grid table.
success: function (data) {
var tblHtml="";
$.each(data.DepotDetailsList,function(a,b){
tblHtml+= "<tr><td>"+b.DepotID+"</td>";
tblHtml+= "<td>"+b.ColumnName+"</td>";
tblHtml+= "<td>"+b.Country+"</td>";
tblHtml+= "<td>"+b.CountryCode+"</td>M/tr>";
});
$("#Grid > tbody").html(tblHtml);
},
Since you already have the partial view which build the table, you can do this.
In your ajax success method call a controller action by passing this data received from the API. The controller will just return the existing partial view by passing the same model.
$.ajax({
url: "/api/Admin/GetDepotDetails/",
type: "POST",
data: { "selectValue": selectValue },
dataType: "json",
success: function (data) {
//$("#Grid").html($(data).children());
$.get("controller/Action",data.DepotDetailsList ,function(response){
$('#tableHolder').html(response) //have a div in your main view which will hold the table. Now the partial view has to be replaced into this div.
});
},
error: function (jqXHR, textStatus, errorThrown) {
debugger;
alert(textStatus, errorThrown, jqXHR);
}
});
So as I said, Create a new MVC action method and return a the same partial view by passing the model sent from ajax.
OR you can user Jquery and build the table again - But this is a pain if the table HTML is large (with css, attributes, dynamic arributes etc). - I think the other answer already has the details on this
I am using asp.net MVC 5.
In Bootbox js
$(document).on("click", ".MyLink", function (e) {
bootbox.confirm("Are you sure?", function(result) {
Example.show("Confirm result: "+result);
});
});
#Html.ActionLink("Delete", "Delete", new { id = item.CustomerID }, new { #class = "MyLink" })
How to delete the HTML action link ?
Please find the full details of the code:-
Javascript code:-
<script src="~/Scripts/bootbox.min.js"></script>
$(document).on("click", ".MyLink", function (e) {
var self = this;
bootbox.confirm("Are you sure?", function (result) {
Example.show("Confirm result: " + result);
$(self).remove();
});
});
HTML Code:-
<h2>Index</h2>
<p>Content here. <a class="MyLink" href=#>Alert!</a></p>
<p>
#Html.ActionLink("Create New", "Create")
</p>
Also see the inside<table> code for your
reference:-
<table class="table">
<tr>
<th> First Name </th>
<th> Last Name </th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td> #Html.DisplayFor(modelItem => item.FirstName) </td>
<td> #Html.DisplayFor(modelItem => item.LastName) </td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.CustomerID }) |
#Html.ActionLink("Details", "Details", new { id = item.CustomerID }) |
#*#Html.ActionLink("Delete", "Delete", new { id = item.CustomerID, #class = "MyLink" })*#
Delete
</td>
</tr>
}
Also see the Controller code for your reference:-
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
db.Customers.Remove(customer);
db.SaveChanges();
if (customer == null)
{
return HttpNotFound();
}
return RedirectToAction("Index");
//return View(customer);
}
How do I actually retrieve the Primary Key (model.ID) of the selected row from my table. And i want to make same cases if a single row is selected button A B C are enabled but if multiple rows are selected only button c is enabled , a and b will be disabled.
I posted my coding below.
$(document).ready(function () {
var table = $('#LineTables').DataTable();
$('#LineTables tbody').on('click', 'tr', function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
});
});
});
<table id="LineTables" class="display dataTable">
<thead>
<tr>
<th>#Html.DisplayNameFor(model => model.Priority)</th>
<th>#Html.DisplayNameFor(model => model.ProductionOrderNumber)</th>
<th>#Html.DisplayNameFor(model => model.SalesOrder.Product.ProductGroup.Name)</th>
<th>#Html.DisplayNameFor(model => model.SalesOrder.Product.ProductName)</th>
<th>#Html.DisplayNameFor(model => model.Quantity)</th>
<th>#Html.DisplayNameFor(model => model.SalesOrder.Product.Pole)</th>
<th>#Html.DisplayNameFor(model => model.SalesOrder.Product.Amperage)</th>
<th>#Html.DisplayNameFor(model => model.SalesOrder.SalesOrderType1.Name)</th>
<th>#Html.DisplayNameFor(model => model.SalesOrder.Market)</th>
<th>#Html.DisplayNameFor(model => model.ProductionOrderStatu.Name)</th>
<th>#Html.DisplayNameFor(model => model.SalesOrder.SalesOrderNumber)</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#Html.DisplayFor(modelItem => item.Priority)</td>
<td>#Html.DisplayFor(modelItem => item.ProductionOrderNumber)</td>
<td>#Html.DisplayFor(modelItem => item.SalesOrder.Product.ProductGroup.Name)</td>
<td>#Html.DisplayFor(modelItem => item.SalesOrder.Product.ProductName)</td>
<td>#Html.DisplayFor(modelItem => item.Quantity)</td>
<td>#Html.DisplayFor(modelItem => item.SalesOrder.Product.Pole)</td>
<td>#Html.DisplayFor(modelItem => item.SalesOrder.Product.Amperage)</td>
<td>#Html.DisplayFor(modelItem => item.SalesOrder.SalesOrderType1.Name)</td>
<td>#Html.DisplayFor(modelItem => item.SalesOrder.Market)</td>
<td>#Html.DisplayFor(modelItem => item.ProductionOrderStatu.Name)</td>
<td>#Html.DisplayFor(modelItem => item.SalesOrder.SalesOrderNumber)</td>
<td>
#Html.ActionLink("New Barcode", "Barcode", new { id = item.ID }, new { #class = "barcode btnic btnicon" })
</td>
</tr>
} </tbody>
</table>
#Html.ActionLink("A", "Index", "A", .......... , new { #class = "btn btn-default btn-ms" })
#Html.ActionLink("B", "Index", "B", .......... , new { #class = "btn btn-default btn-ms" })
#Html.ActionLink("C", "Index", "C", .......... , new { #class = "btn btn-default btn-ms" })
Based comments above:
Firstly you cant use #Html.ActionLink(..) for the 'buttons (these are rendered on the server side and you dont know the selected ID at that point) - use a html <button id="edit">Edit</button>. In the row.click function, test the number of selected rows and enable/disable the buttons as required
var selectedRows = $(this).closest('tbody').children('tr')
.filter('.selected').length;
if (selectedRows = 1) {
// enable edit and details buttons
} else {
// disable edit and details buttons
}
Then in the click events for each button (edit button shown)
$('#edit').click(function() {
var ID = $(this).find('input[type="hidden"]').val(); // as per first answer
window.location.href = '/yourController/edit/' + ID;
return false;
});
The delete button will be a little more complicated - one way would be to loop the selected rows, get the ID and use AJAX to post the ID to your 'Delete' action method, then in the success function, delete the row from your table, for example (not tested)
var url = "#Url.Action("Delete")"; // your delete action
$('#delete').click(function() {
$('#LineTables').children('tbody').children('tr')
.filter('.selected').each(function) {
var row = $(this);
var ID = row.find('input[type="hidden"]').val();
$.post(url, { ID = ID }, function() {
row.remove();
});