AlexGH AlexGH - 17 days ago 5
Javascript Question

Add link with attributes contained in a row to a table using JQuery

I'm trying to add a row to a table, I can do that, the problem is that the row should contains a link on it and the link should have some parameters. Something like this :

var $row = $("<tr>" + "<td>" + "<div style=\"border-top:3px;padding-top:3px\">" + $("<a>" + result.fileName + "</a>").attr({ href: "/AgencyNotes/OpenFile/" + result.fileName + "/" + result.agencyNoteId }) + "</div>" + "</td>" + "</tr>")

$(temp).children().children().children().children().first().after($row)


I have tried this other code but what I get in la table is just
[object Object]
:

var $row = $("<tr>" + "<td>" + "<div style=\"border-top:3px;padding-top:3px\">" + $("<a>" + result.fileName + "</a>").attr({ href: $(".link_open_file").data("url") }).data({"fileName":result.fileName, "noteId":result.agencyNoteId }) + "</div>" + "</td>" + "</tr>")

$(temp).children().children().children().children().first().after($row)


The row is being added correctly but the link is not working, which is the best approach to do this using JQuery?
By the way this is my controller action:

public ActionResult OpenFile(string fileName, int noteId)
{
}


I prefer something like the second approach to not harcode the url ...
I'm getting the url from the html page:

@Html.ActionLink(file.FileName, "OpenFile", new { fileName = file.FileName, noteId = file.AgencyNoteId, @class="link_open_file", data_url=Url.Action("OpenFile","AgencyNotes") })

Answer

What if you wrote your anchor tag like this:

"<a href='/AgencyNotes/OpenFile/" + result.fileName + "/" + result.agencyNoteId + "'>" + result.fileName + "</a>"

In your code:

var $row = $("<tr>" + "<td>" + "<div style=\"border-top:3px;padding-top:3px\">" + "<a href='/AgencyNotes/OpenFile/" + result.fileName + "/" + result.agencyNoteId + "'>" + result.fileName + "</a>" + "</div>" + "</td>" + "</tr>")

EDIT: to include AlexGH's comment for the complete solution:

"It works after I added a new Route to the RouteConfig file, like this:"

routes.MapRoute("OpenFile", "{controller}/{action}/{fileName}/{noteId}", new { ontroller = "AGgencyNotes", action = "OpenFile"}, new[] { "Project.Controllers" }); 
Comments