【问题标题】:Is there a way to concatenate strings in html attributes?有没有办法在 html 属性中连接字符串?
【发布时间】:2011-10-04 00:09:06
【问题描述】:

我正在使用 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 为 1,但在浏览器的 HTML 中,我目前得到:

id="label"+"1"

所以如果我尝试做类似的事情:

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

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

那么我怎样才能将这两个字符串加在一起形成一个连贯的字符串,可以被 jQuery(或 document.getElementByID(str) 识别)。

【问题讨论】:

    标签: html asp.net-mvc-3


    【解决方案1】:

    试试这个(已验证):

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

    【讨论】:

    • 成功了:&lt;div id="@("label"+Model.Id)" class="display-field"&gt;@Model.InitValue&lt;/div&gt; 非常感谢。
    • 刚刚添加了引号(在您发表评论时):)
    • 是的,我看到了。不过,感谢您的帮助。我还是 MVC3 和 Razor 语法的新手。
    【解决方案2】:

    你想要:

    <div id="label@Model.Id" ...
    

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

    编辑:

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

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

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

    【讨论】:

    • 我试过了。在我浏览器的 HTML 源代码中,id 只是“label@Model.Id”
    【解决方案3】:

    只需添加另一个选项,因为当我尝试将字符串和模型值连接为@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()) })
    

    【讨论】:

      【解决方案4】:

      这是你需要做的。

      id="label_@Model.Id"
      

      下划线(_)是必需的。对我来说,在没有下划线的情况下传递 id 会产生问题。祝你好运。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-10
        • 1970-01-01
        • 1970-01-01
        • 2014-06-02
        • 2021-12-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多