views:

29

answers:

1

I'm writing a jQuery grid plugin and I've designed it so it works independently from the language being used. The following is the basics of how my plugin is assigned:

$("#grid").grid({
    enablePager: true,
    dataPath: "Movement/GetGridPage",
    columns: {
        Edit: { title: "", cellCallback: editButtonCallBack, width:"16px" },
        DocketNumber: { title: "Docket #" },
        SiteName: { title: "Site" },
        SiteAddress: { title: "Address" },
        SiteRegion: { title: "Region" },
    },
    cssTable: "table",
    cssAltRow: "altRow"
});

Because I want to perform some more advanced data handling than just populating a <td> with some text, I've added a callback handler (cellCallback) which allows me to have a page specific function for a particular columns data. So within my plugin I do the following:

var dataItem = currentRow[columnName];
if (columnSetting.cellCallback) {
    $td.html(columnSetting.cellCallback(dataItem));
}
else {
    $td.html(dataItem);
}

The problem I've got is that my edit column needs to contain some ImageActionLinks (my Image implementation of an ActionLink). I don't want to return the HTML within my JSON response from the Controller because that's an unnecessary overhead.

Is there any nice way I can create these action links on the fly? Currently, to get it working, I have this incredibly nasty method:

function editButtonCallBack(data)
{
    var link = '<%= Html.ImageActionLink("Movement", "Edit", new { id = "X" }, 
        Url.Content("~/Content/Icons/Edit.png"), "Edit", null, null) %>';
    return link.replace("X", data);
}

So on each callback, I just find and replace the X with the data that represents the ID to edit.

I know this is bad and will break as soon as the Controller or Action has an X in it. So how can I do this properly?

+1  A: 

What about:

function editButtonCallBack(data)
{
    var link = '<%= Html.ImageActionLink("Movement", "Edit", null, 
        Url.Content("~/Content/Icons/Edit.png"), "Edit", null, null) %>';

    var element = $('<div>' + link + '</div>');
    element.find('a').attr('id', data)
    return element.html();
}

This will at least perform the replacement on that specific attribute rather than on the entire block of HTML. (Surrounding with the "<div></div>" because html() only grabs the inner HTML.)

Kirk Woll
I take it you meant `href` instead of `id`? Did the following thanks to this answer: `anchor.attr('href', anchor.attr("href") + "/" + data)`.
GenericTypeTea
Oh? From your code in your question, it looked like you were only replacing the value of the *id* attribute. But anyway, glad I could help. :)
Kirk Woll
@Kirk Woll - It's an ActionLink, so the id is the name of the property on the controller action, not the ID of the element.
GenericTypeTea