Search code examples
javascriptasp.net-mvc-4backbone.jsunderscore.js

How to render Url.Action with data in an Underscore.js template?


I am trying to download a JSON file when we click on download button.

public ActionResult getJsonFile(Guid ProtocolId)
{
    List<Country> lst = new List<Country>();
    for (int i = 1; i <= 10; i++)
    {
        lst.Add(new Country() { CountryId = i, CountryName = "India" + i });
    }
    string jsondata = new JavaScriptSerializer().Serialize(lst);
    byte[] bytes = System.Text.Encoding.ASCII.GetBytes(jsondata);
    return File(bytes, "application/json", "JsonData.json");
}

This code works fine for me, if I don't send any parameter (ProtocolId) to this method.

<script type="text/ng-template">
    <button type="button" onclick="location.href='@Url.Action("getJsonFile", "Home")">Download</button>
</script>

Here, the protocolid needs to be bound using these tags <%= protocolid %> (Underscore.js template) as I am using Backbone.js as client side script.

How can I bind the protocolid to the anchor tag so that when user clicks on Download link it should send the protocolid to the getJsonFile() method?


Solution

  • Assuming the url returned by @Url.Action("getJsonFile", "Home") is of the following form /home/json-file/ and that you're looking to get:

    /home/json-file/1234
    

    You could just append the id:

    <a href="@Url.Action("getJsonFile", "Home")<%= protocolid %>">Download</a>
    

    If the id is within the url, I think you can put an arbitrary string as the id in Url.Action (not tested):

    @Url.Action("getJsonFile", "Home", new { id = "<%=protocolid%>" })
    

    So it generates the tags at the right place, e.g.:

    /home/get-json/<%=protocolid%>/download/
    

    So when rendered with underscore, the <%=protocolid%> is replaced correctly.