简体   繁体   English

如何使用Underscore.js模板中的数据渲染Url.Action?

[英]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. 我在点击下载按钮时尝试下载JSON文件。

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. 如果我不向此方法发送任何参数( ProtocolId ),此代码对我来说很好。

<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. 这里, protocolid需要使用这些标签被绑定<%= protocolid %>如我使用Backbone.js的作为客户端脚本(Underscore.js模板)。

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? 如何将protocolid绑定到锚标记,以便当用户单击“ Download链接时,它应该将protocolid发送到getJsonFile()方法?

Assuming the url returned by @Url.Action("getJsonFile", "Home") is of the following form /home/json-file/ and that you're looking to get: 假设@Url.Action("getJsonFile", "Home")返回的url具有以下形式/home/json-file/并且您希望获得:

/home/json-file/1234

You could just append the id: 你可以添加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) : 如果id在url中,我认为你可以在Url.Action (未测试) Url.Action任意字符串作为id:

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

So it generates the tags at the right place, eg: 所以它在正确的位置生成标签,例如:

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

So when rendered with underscore, the <%=protocolid%> is replaced correctly. 因此,当使用下划线渲染时, <%=protocolid%>会被正确替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM