Search code examples
javascriptc#asp.netstringrazor

returning a string containing href="@Url.Action in anchor tag


function iconFormatter(value, row, index) {
    var idNode = row.nodeId;
    if (row.isFile === true) {
        return '<img src="../Test/file.png" style="margin-left: 10px;" /><a class="file-download" href="@Url.Action("DownloadFile", "Casename", new { fileId = "' + row.nodeId + '" })"> ' + value + '</a>'
    }
    return value
}

In fileId = "' + row.nodeId + '", row.nodeId is returning the hex string value instead of int value.

Can someone please suggest the required correction here?


Solution

  • You're mixing server-side and client-side code. The two execute at entirely different times in entirely different contexts (often on entirely different computers).

    Instead, use the server-side code to generate the URL with a known placeholder, then you can replace that placeholder in the client-side code. For example:

    function iconFormatter(value, row, index) {
      // generate the URL from server-side code
      // (hint: view the page source in the browser and see what this becomes)
      let url = '@Url.Action("DownloadFile", "Casename", new { fileId = "PLACEHOLDER" })';
    
      if (row.isFile === true) {
        // replace the placeholder
        url = url.replace('PLACEHOLDER', encodeURIComponent(row.nodeId));
    
        // use the resulting URL
        return '<img src="../Test/file.png" style="margin-left: 10px;" /><a class="file-download" href="' + url + '"> ' + value + '</a>'
      }
      return value
    }
    

    (If one were to look only at the client-side code this result might look unnecessary. That's because to the client-side code these are all string literals. The client-side code is unaware of the server-side functionality of @Url.Action.)