在jquery.tmpl模板中使用MVC帮助器 [英] Use MVC helpers inside jquery.tmpl templates

查看:67
本文介绍了在jquery.tmpl模板中使用MVC帮助器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的foreach模板,并且在每个元素中我都想要一个ActionLink,但是ActionLink需要发送一个ID来编辑该元素.

I have a simple foreach template and inside every element I want an ActionLink but that ActionLink needs to send an Id to edit the element.

要模板化的项目:

<div data-bind="template: {
                    name: 'postsTemplate',
                    foreach: posts
                    }">
</div>

模板:

<script id="postsTemplate" type="text/html">
<h2 data-bind="text: Title"></h2>

<p class="post-info">
    <p class="post-info" data-bind="text UserName"></p>
    <span data-bind="Body"></span>
    <p class="post-footer">
        @Html.ActionLink("Comments", "IndividualPost", "Post", null, null, "comments", new {id = })
    </p>
</p>
</script>

如何通过ActionLink发送实际的帖子Id?我的意思是,如何不使用数据绑定即可访问帖子的ID? (因为它是一个助手).

How can I send the actual post Id through the ActionLink? I mean, How I can access to the post's id without using data-bind? (Because it's a helper).

推荐答案

如果您要沿着以下行实现自己的ActionLink扩展:

If you would implement your own ActionLink extension along the line of:

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText,
                                       string actionName, string controllerName,
                                       object routeValues,  bool noEncode)
    {
        var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
        var url = urlHelper.Action(actionName, controllerName, routeValues);

        if (noEncode) url = Uri.UnescapeDataString(url);

        var tagBuilder = new TagBuilder("a");

        tagBuilder.MergeAttribute("href", url);
        tagBuilder.InnerHtml = linkText;

        return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
    }

然后,您可以将模板制作为:

Then you could make your template like:

<p class="post-info">
    <p class="post-info" data-bind="text UserName"></p>
    <span data-bind="Body"></span>
    <p class="post-footer">
        @Html.ActionLink("Comments (${CommentCount})", "IndividualPost", "Post", 
                         new {id = "${id}"}, true)
    </p>
</p>

生成的服务器端html如下所示:

the serverside html generated would then look like:

<p class="post-info">
    <p class="post-info" data-bind="text UserName"></p>
    <span data-bind="Body"></span>
    <p class="post-footer">
       <a href="/Post/IndividualPost/${id}">Comments (${CommentCount})</a>
    </p>
</p>

在我看来,这又是一个完美的模板.

which in turn is a perfect template in my opinion.

ActionLink扩展的原因是普通的Html.ActionLink将您的url编码为/Post/IndividualPost/%24%7Bid%7D,这不适用于模板

The reason for an ActionLink extension is the fact that the normal Html.ActionLink encodes your url to /Post/IndividualPost/%24%7Bid%7D which doesn't work for the template

这篇关于在jquery.tmpl模板中使用MVC帮助器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆