I want to update a column of data in a table in MVC view.
This is the View that I want to update.
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CurrentTemperature)
</th>
<th></th>
</tr>
#{int i = 1;}
#foreach (var item in Model)
{
<tr>
<td align="center" #*id="#("current"+i)" data-id="#item.ID"*#>
<div id="#("current"+i)" data-id="#item.ID">
#{Html.RenderAction("TemperatureUpdateDeviceList", new { idDevice = item.ID });}
</div>
</td>
</tr>
i++;
}
</table>
I wrote a simple script in order to update the divs. Just for trying I decided to update only the 4th div with id= current4.
$(function () {
setInterval(function () {
var id = $(this).attr('data-id');
$.ajax({
url: '#Url.Action("TemperatureUpdateDeviceList")',
type: 'GET',
data: { idDevice: id},
}).success(function (partialView) {
$('#current4').html(partialView);
});
},3000);
});
Using this method I can't perform a correct request because the generated URL is not correct. How to have a correct URL?
Notice that TemperatureUpdateDeviceList function is defined as:
public PartialViewResult TemperatureUpdateDeviceList(int idDevice)
{
return PartialView(temperatureModel);
}
You use of var id = $(this).attr('data-id'); will not pass the data-id value because $(this) is not your <div> element. If you want to update all your elements, then change the html to
<div class="container" data-id="#item.ID">
#{Html.RenderAction("TemperatureUpdateDeviceList", new { idDevice = item.ID });}
</div>
Note the id attribute is not necessary. Then in the script use
var url = '#Url.Action("TemperatureUpdateDeviceList")';
setInterval(function () {
$('.container').each(function() {
var id = $(this).data('id');
var div = $(this);
$.get(url, { idDevice: id}, function(partialView) {
div.html(partialView);
});
});
},3000);
Related
On my view page I have a table (from a partial view) and a form. I am using ajax to submit the form to my webapi controller.
On success I would like to add what was entered in the textbox to the first column, and links to Edit and Delete in the second column of a new row.
As of right now I am only working on the Edit link.
Here is my partial view table:
<table id="Table" class="table table-bordered">
<thead>
<tr>
<th class="col-md-6">
#Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
</thead>
#foreach (var item in Model)
{
<tr>
<td class="col-md-6">
#Html.DisplayFor(modelItem => item.Admin)
</td>
<td class="col-md-6">
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</table>
Here is my form jquery.ajax:
var table = $("#Table").DataTable({
"aoColumnDefs": [
{ "bSortable": false, "aTargets": [1] },
{ "bSearchable": false, "aTargets": [1] }
]
});
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
url: infoGetUrl,
method: "post",
data: $("form").serialize()
}).success(function (data) {
var editLink = document.createElement('a');
editLink.href = "/controllerName/Edit/" + data.id;
editLink.text = "Edit";
table.row.add([
$("#Textbox").val(),
editLink
]).draw();
}).error(function(jqXHR, textStatus, errorThrown) {
console.log("error");
});
});
The problem is that when this renders I get this:
It is not clickable and renders like this:
<tr class="even" role="row">
<td class="sorting_1">John.Doe</td>
<td>http://localhost:61888/controllerName/Edit/15</td>
</tr>
As you can see, it is not rendered in an a tag, and I don't need the http://localhost:61888 part of the link.
How can I resolve this?
try creating link as:
var link = <a href='/controllerName/Edit/' + data.id>EDIT</a>
With pur JS:
var link = document.createElement('a');
link.textContent = 'Edit';
link.href = "/controllerName/Edit/" + data.id;
you just need to place this inside your td.
If you want to remove 'http://localhost:61888' you can just use replace to change your localhost by un empty string. Or split your string and just keep the second part
<script type="text/javascript">
function LoadData(){
var url = serverURL+"/List.php";
$.ajax({
type: "GET",
url: url,
dataType: "json",
success: function(data){
$.each(data.data, function (key, value) {
var doc_id=value['id'];
var doc_name=value['name'];
var doc_speci = value['specialize'];
$("#myTable").append("<tr><td>"+doc_name+"</td><td>"+doc_speci+"</td><td class='retrieve' data-did="+doc_id+" style='cursor: pointer;'>EDIT</td></tr>");
});
},
error: function(data){
toastr.error("Opps! Something went wrong");
$(".se-pre-con").fadeOut("slow");
},
});
}
</script>
The above appends a tr to my html table below.
The HTML TABLE is as follows:
<table id="myTable" class='table table-bordered table-hover table-striped'>
<tr>
<th>Name</th>
<th>Specialization</th>
<th>Action</th>
</tr>
</table>
Now i want to retrieve the id from the data attribute from td class retrieve so that i can send the id and redirect it to other page for editing.
// Clicks the edit field
$("td.retrieve").on("click", function(e) {
var id = $(e.currentTarget).attr("data-did");
// do with the ID what you want
alert(id);
});
I'm aware that jQuery has a "data(...)" function but I've run into issues with that sometimes in the past. "attr(...)" will do something similar but relies specifically on the attribute instead of stored objects.
First, to add your data attribute you should make sure you add quotes around the value:
data-did='"+doc_id+"'...
So the rendered cell must look something like this:
<td class='retrieve' data-did='n' style='cursor: pointer;'>EDIT</td>
(where n is some value)
Then you can easily retrieve this value with jQuery:
$('specific-td').data('did'); //specific-td referes to a specific cell in a row, you must write that, this is just an example
To get all of the rows:
var ids = [];
$('.retrieve').each(function() {
ids.push($(this).data('did'));
});
Example:
If you have a button for example:
$('#myTable').on('click', '.retrieve input[type="button"]', function() {
var id = $(this).parent().data('did');
alert(id);
});
JSFiddle: https://jsfiddle.net/y2an0fu7/1/
I have two partial views, one is _UserList and the other one is _UserDetail and both of them are shown in index.
[index.cshtml]
#Styles.Render("~/Content/PagedList.css")
<h2>UserManagement</h2>
<hr />
<div id="UserList">
#Html.Partial("_UserList")
</div>
<hr />
<div id="UserDetail"></div>
<hr />
I already have a link named Details that is implemented with Ajax.ActionLink to show the detail in every rows.
And the link's source code is:
[_UserList.cshtml]
#Ajax.ActionLink("Details", "UserDetail", new { userId = item.ID }, new AjaxOptions { HttpMethod = "GET", InsertionMode = InsertionMode.Replace, UpdateTargetId = "UserDetail" })
After click "Details", _UserDetail will be shown under _UserList.
Now, I want to implement a clickable row that can load _UserDetail with a parameter: item.ID when I click on a row of the table in _UserList.
I have tried a lot of ways but I still cannot implement it successfully.
Could anyone give me a hand?
Finally, I found a way to implement this feature with jQuery.
And the source code is as below:
<table class="table table-hover>
#foreach (var item in Model.TlmAbstractPagedList)
{
<tr data-id="#item.TlmId" class="clickableRow">
<td>
#Html.DisplayFor(u => item.DateStart) ~ #Html.DisplayFor(u => item.DateEnd)
</td>
<td>
#Html.DisplayFor(u => item.Name)
</td>
<td>
#foreach (var product in item.ProductInformation)
{
<ul>product.ProductNameWithId</ul>
}
</td>
</tr>
}
</table>
<script>
$('.clickableRow').click(function () {
var targetRow = $(this).data('id');
$.ajax({
url: 'TlmManagement/TlmReport',
data: { tlmId: targetRow },
method: "GET",
success: function (data) {
$("#TlmDetail").empty();
$("#TlmReport").empty();
$("#TlmReport").html(data);
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
})
</script>
I assign data-id to every row and the class click function will check this data-id to find out which row is being clicked and then make display of the data.
Hope this source code will help someone.
I am trying to add new rows to the table using the rows.add() function in the DataTables API. The data is coming from the server using AJAX call.
Here is an example to work upon - FIDDLE
My Table Structure is follows:
<table id="myTable">
<thead>
<th>
Id
</th>
<th>
Name
</th>
<th>
Designation
</th>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.Number
</td>
<td>
#item.Name
<img id="imgA" onclick="AddNewRows();" class="iterationChild" src="#Url.Content("~/Images/plus.png")" alt="expand/collapse" />
</td>
<td>
#item.Designation
</td>
</tr>
}
</tbody>
</table>
Corresponding Javascript function:
function AddNewRows() {
$.ajax({
type: 'GET',
url: '#Url.Action("NewRows", "Home")',
dataType: "json",
async: true,
success: function (data) {
var table = $('#myTable').DataTable();
for (var i = 0, l = data.length; i < l; i++) {
//how to add it just after the current row clicked
table.row.add([
data[i].Number,
data[i].Name,
data[i].Designation
]).draw();
}
},
error: function (result) {
alert('error');
}
});
}
I want to be able to add the new row after the row which is clicked. Here it is adding at the end of the table(last rows).
Assuming every row as a unique id, try passing the current row clicked id into your function as a parameter. Example:
function AddNewRows(id) {
var my_row = document.getElementById(id);
...
I am adding a button that will "approve" all rows in the table (call a URL to process the record). I generate the table then attach the DataTable to the prefilled table. On each tr I have the id number of the record.
<tr id="11309742">
<td>blah</td>
<td>blah</td>
<td>blah</td>
</tr>
<tr id="11309743">
<td>blah</td>
<td>blah</td>
<td>blah</td>
</tr>
Here is what I have so far:
$.each(table.fnGetData(), function (i, row) {
var id = $(this).attr("id");
$.get(myUrl, { id: id },
function (json) {
if (json.Sucess) {
// TODO remove from the page
}
}, "json");
});
var id = $(this).attr("id"); worked before I switched to the datatable plugin (and I know it won't work now). Everything I have seen is either setting the id or getting the index from a click in the row. How do I get that id attribute in a loop?
Instead of using .fnGetData(), I should have used .fnGetNodes().
$.each(table.fnGetNodes(), function (i, row) {
var id = $(this).attr("id");
$.get(myUrl, { id: id },
function (json) {
if (json.Sucess) {
//table.fnDeleteRow(i);
}
}, "json");
});
Now it works as expected.