ASP.NET MVC: How to call javascript function in Html.ActionLink
When I edit single recored in page, I use checkbox to get a selected row not every row with an actionlink element, but it seemed I cant make this way happen through calling javascript code (function GetSelectedRow() should return an id). Could anyone have a nice idea?
<head runat="server">
<title>Index</title>
<script type="text/javascript" language="javascript">
function GetSelectedRow() {
var a = 0;
var chkBoxes = document.getElementsByName("chkSelect");
var count = chkBoxes.length;
for (var i = 0; i < count; i++) {
if (chkBoxes[i].checked == true)
a = chkBoxes[i].primaryKeyID;
}
return a;
}
</script>
</head>
<body>
<div>
<span style="width:20%">
<%: Html.ActionLink("Add", "Create")%>
</span>
<span>
<%: Html.ActionLink("Edit", "Edit", new { id = GetSelectedRow()) %>
</span>
<span>
<%: Html.ActionLink("Detial", "Details", new { id = GetSelectedRow() })%>
</span>
<span>
<%: Html.ActionLink("Delete", "Delete", new { id = GetSelectedRow()) %>
</span>
</div>
<table>
<tr>
<th></th>
<th>
CategoryID
</th>
<th>
CategoryName
</th>
<th>
Description
</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%: Html.ActionLink("Details", "Details", new { id = item.AppCategoryID })%>
</td>
<td>
<%: Html.CheckBox("chkSelect", false, new { primaryKeyID = item.AppCategoryID })%>
</td>
<td>
<%: item.AppCategoryID %>
</td>
<td>
<%: item.AppCategoryName %>
</td>
<td>
<%: item.Description %>
</td>
</tr>
<% } %>
</table>
</body>
你可以做这样的事情:
<script type="text/javascript">
function RedirectUsingSelectedRow() {
var id = GetSelectedRow();
window.location = '../Controller/Details/' + id;
}
</script>
<a href="#" onclick = "RedirectUsingSelectedRow();">Edit</a>
Mixing server and client that way won't work. What you need to do, when a row is selected, is to manipulate the URL. So rather than return a URL, have GetSelectedRow do:
function GetSelectedRow() {
//existing logic minus return
var link1 = document.getElementById("Link1"); //this would require giving links an ID
link1.href = '<%= Url.Action("Detail", new { controller = "Details" }) %>' +
'id=' a.toString();
}
You have to change it from client-side javascript is the key, rather than doing that during the rendering process.
HTH.
Try this -
$('#GetSelectedRow').click(function() { /* Your Code */ });
Calling java script function by id 'GetSelectedRow'. Instead of calling the function by id, you can directly call the function
<% Html.ActionLink("Edit", "Edit", "Controller", new { onclick = "GetSelectedRow();"}) %>
链接地址: http://www.djcxy.com/p/30988.html