双引号之间的 Razor 代码

发布于 2024-10-03 19:35:24 字数 498 浏览 0 评论 0原文

在 Razor View Engine 模板中,我想要执行以下操作:我想要在 html 属性 的双引号之间放置一些代码。问题是我想要插入的代码片段本身包含一些双引号。

<a href="Url.Action("Item", new { id = Model.Item.Id, page = page });">@page</a>

你可以很容易地看到事情是如何变得非常错误的:-)我知道我可以计算变量中的链接然后使用它,但我宁愿不:

@{ var action = Url.Action("Question", new { id = Model.Question.Id, page = page }); }                   
<a href="@action">@page</a>                                        

In a Razor View Engine template, I want to do the following: I want to put some code between the double quotes of an html attribute. The trouble is that the piece of code I want to insert contains some double quotes itself.

<a href="Url.Action("Item", new { id = Model.Item.Id, page = page });">@page</a>

You can easily see how things turn horribly wrong :-) I know i can calculate the link in a variable and then use it, but I'd rather not:

@{ var action = Url.Action("Question", new { id = Model.Question.Id, page = page }); }                   
<a href="@action">@page</a>                                        

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

醉梦枕江山 2024-10-10 19:35:24

你不需要使用 Razor 进行逃脱或任何操作。 Razor 足够聪明,可以知道引号何时位于属性内,因为在解析它时,您正在将其转义到 html 之外。

<a href="@Url.Action("Item", 
       new { id = Model.Item.Id, page = page })">@page</a>

该代码可以正常工作 - 只需确保在 Url.Action 调用前面有 @ 符号,因为如果不这样做,它将无法正确解析,并且我注意到你的问题中没有这个。

编辑:删除;因为 Url.Action 不是一个声明。

You don't need to escape or anything using Razor. Razor is smart enough to know when quotes are within attributes because you're escaping outside of html when you parse it.

<a href="@Url.Action("Item", 
       new { id = Model.Item.Id, page = page })">@page</a>

That code will work fine - Just make sure you have the @ symbol in front of the Url.Action call because if you don't it won't be parsed properly and I notice you don't have it in your question.

Edit: removed ; as Url.Action is not a statement.

无人接听 2024-10-10 19:35:24

也许我不明白你的问题,在这种情况下请纠正我,但你不能简单地:

@Html.ActionLink(page, "Question", new { id = Model.Question.Id, page = page })

Maybe I didn't understand your question in which case please correct me but can't you simply:

@Html.ActionLink(page, "Question", new { id = Model.Question.Id, page = page })
懷念過去 2024-10-10 19:35:24

这可能是正确的:

href="@(action)"> @page 

This may be correct :

href="@(action)"> @page 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文