有没有办法在 html 属性中连接字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6671086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 09:32:23  来源:igfitidea点击:

Is there a way to concatenate strings in html attributes?

htmlasp.net-mvc-3

提问by user558594

I'm using MVC3 and I wanted to use a partial view to create dynamic DOM elements. This is my current partial view:

我正在使用 MVC3,我想使用局部视图来创建动态 DOM 元素。这是我目前的部分观点:

@model MVCApp.ViewModels.TitlesViewModel

<div class="display-label">Name</div>
<div id="label"+"@Model.Id" class="display-field">@Model.InitValue</div>

Model.Id is 1 but in the HTML in the browser, I currently get:

Model.Id 是 1 但在浏览器的 HTML 中,我目前得到:

id="label"+"1"

So if I try and do something like:

因此,如果我尝试执行以下操作:

alert($("#label1").text())

There's an alert box with nothing in it.

有一个警告框,里面什么都没有。

So how can I add the two strings together to form one coherent string that is recognized by jQuery (or document.getElementByID(str) for that matter).

那么如何将这两个字符串加在一起以形成一个由 jQuery 识别的连贯字符串(或 document.getElementByID(str) 就此而言)。

回答by Mrchief

Try this (verified):

试试这个(已验证):

<div id="@("label"+Model.Id)" class="display-field">@Model.InitValue</div>

回答by Steve Morgan

You want:

你要:

<div id="[email protected]" ...

Razor will recognise the @ as the start of code, execute it and render the results in place in the attribute.

Razor 会将 @ 识别为代码的开始,执行它并将结果呈现在属性中。

Edit:

编辑:

This didn't work well as a comment, but here's a line from one of my Razor controls:

这作为评论效果不佳,但这是我的一个 Razor 控件中的一行:

<input type="text" readonly="readonly" 
       class="display-field [email protected]" 
       id="@((ViewData["id"] == null) ? 
         ViewData.ModelMetadata.PropertyName : ViewData["id"])"
       value="@Proj.GetJobStatusValue(Model)" />

Try adding a hyphen (-) before the @. It's quite possible that Razor thinks it's an e-mail address and leaving it alone!

尝试在@ 之前添加一个连字符 (-)。Razor 很可能认为这是一个电子邮件地址,而不管它!

回答by craigvl

Just adding another option as this is what worked for me when trying to concat string and model value as id in an @html.ActionLink and also for the text value. I needed to use string.Concat. Don't know if this is bad from a performance point of view.

只需添加另一个选项,因为当我尝试将字符串和模型值连接为 @html.ActionLink 中的 id 以及文本值时,这对我有用。我需要使用 string.Concat。不知道从性能的角度来看这是否很糟糕。

  @Html.ActionLink(string.Concat("View all (", @Model.FooCount, ")"),
        //actionName        
        "SeeAllFoos",
        //ControllerName
        "Foo",
        // routeValues
        new { FooId = @Model.Foo.id },
        //htmlAttributes
        new { @class = "btn btn-success", onclick = "ShowProgress();",
        id = string.Concat("Foo",@Model.Foo.id.ToString()) })