Reputation: 610
I am new to MVC and JQuery.
I have created one table with JQuery but I don't know how we add one actionlink
in each row, and also, I need to call one partial view on the onclick
event by passing the Java script variable to the partial view.
My code is given bellow:
function loadData(data) {
var tab = $('<table class="myTable"></table>');
var thead = $('<thead></thead>');
thead.append('<th>Id</th><th></th>');
thead.append('<th>Username</th>');
tab.append(thead);
$.each(data, function (i, val) {
var trow = $('<tr></tr>');
trow.append('<td>' + val.empID + '</td>');
trow.append('<td>' +"" + '</td>');
trow.append('<td>' + val.empName + '</td>');
trow.append('<td>' + '@Html.ActionLink("Edit", "Edit", new { id = val.empID })' + '</td>');
tab.append(trow);
});
here I got one error:
val is not in the current context
I checked a lot of similar post here and I understand one part of the code is run at the server (the Url.Action
part) and the val.empID
is only available once the code reaches the client browser.
but I need to load one partial view on click if there is any alternate way to do this......
Upvotes: 1
Views: 912
Reputation: 1097
You can't pass jquery variable to server control change your
trow.append('<td>' + '@Html.ActionLink("Edit", "Edit", new { id = val.empID })' + '</td>');
To
trow.append('<td>' + '<a href='#' class='preview' data-id='+val.empId+'></a>' + '</td>');
Add class in anchor tag preview
and add one attribute data-id
$('#tbId').on("click", ".preview", function (e) {
e.preventDefault();
var id = $(this).attr("data-id");
var url = '@Url.Action("Edit", "Edit")' + '/' + id;
$.get(url, function (data) {
if (data != "") {
$('.preview-body').html(data); // it is my modal
$('#myModal').modal("show"); // show preview in my modalbox
}
});
});
Upvotes: 0
Reputation: 133403
You can't pass client-side JavaScript variable to Server Side Helper function.
As @Html.ActionLink
create an anchor tag, you can create it programatically. Here's an example:
function loadData(data) {
$.each(data, function(i, val) {
//Create Static URL and use -1 as placeholder
var url = '@Url.Action("actionName", "controllerName", new { id = -1 })';
//replace the place holder with the value which you want
url = url.replace('-1', val.empID);
//Generate the anchor
var anchor = '<a class="myClass" href="' + url + '">Edit</a>'
//Append anchor
trow.append('<td>' + anchor + '</td>');
tab.append(trow);
});
}
$(document).on('click', '.myClass', function(evt) {
evt.preventDefault();
//Code to load your partial view
$('#myDiv').load(this.href);
});
Upvotes: 1