Add Link Column to DataTable After Ajax Call MVC - javascript

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

Related

Ajax call returns Object(object), how to get the value from it

JSP file
<div class="container">
<table id="headerTable" class="table table-bordered">
<thead>
<tr>
<th colspan="2">Header</th>
</tr>
</thead>
<tbody>
<c:forEach items="${headerList}" var="field">
<tr>
<th>${field}</th>
<td><input id="${field}" type="text" class="form-control "></td>
</tr>
</c:forEach>
</tbody>
</table>
Javascript
$('#parseBtn').click(function() {
var parseMsg = $('#msgText').val();
alert("parse message is " + parseMsg);
$.ajax({
type: "GET",
url: "/parseMessage",
data: {
"msg": parseMsg
},
success: function(data) {
//data format looks like Object {SubsystemChannel: "F", MessageNumber: "200257", DebugQueue: " ", WorkStationNumber: "023", FrontEndNumber: "0000"…}
$('#headerTable input').each(function() {
var id = $(this).attr('id');
var field = data.id;
$(this).val(field);
});
}
});
});
What I am going to do is, go through the $('#headerTable input'), set the value(from data) in it. So, I get the each input id first, then get the value from data using id, but it failed.... Could you help me on this? thank you very much
You should use Bracket notation instead of dot notation to access properties using id variable
$('#headerTable input').each(function () {
var field = data[$(this).attr('id')];
$(this).val(field);
});

Use selenium webdriver to extract dynamic table displayed on the website

I am trying to parse a website where table content is loaded through javascript-ajax call..
function buildTable() {
// render spinner over dataset summary table
var overlay = document.getElementById("summary");
enableOverlay(overlay, true, true, "30px");
// request dataset summary from server
$.ajax({
url: "/ProteoSAFe/MassiveServlet",
data: { "function":"", "mid":dataset_name },
type: "GET",
cache: false,
complete: function(data) {
var stats = JSON.parse(data.responseText);
var filesize = document.getElementById("filesize");
filesize.innerHTML = stats.filesize;
}
In HTML :
<table>
<table>
<tr>
<td>Number of Files:</td>
<td id="filecount"></td>
</tr>
<tr>
<td>Total Size:</td>
<td id="filesize"></td>
</tr>
<tr id="spectra_row" style="display:hidden">
<td>Spectra:</td>
<td id="spectra"></td>
</tr>
<tr>
<td>Subscribers:</td>
<td id="subscribers"></td>
</tr>
I am using below code in selenium:
List<WebElement> tables = div.findElements(By.tagName("table"));
wait.until(ExpectedConditions.visibilityOfAllElements(tables));
for (WebElement table : tables) {
List<WebElement> allRows = table.findElements(By.tagName("tr"));
for (WebElement row : allRows) {
List<WebElement> cells = row.findElements(By.tagName("td"));
for (WebElement cell : cells) { System.out.println("content >> " + cell.getText());
}
}
}
My question is : Its extracting only couple of table cells ..I want to extract content of all the table.
Is there any other way to extract the table content. Please advise.

How to load a partial view by clicking a row in the table

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.

Auto refreshing multiple divs MVC

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);

Unable to add row in the middle of jQuery datatables(with FIDDLE)

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);
...

Categories