Is there a way to concatenate strings in html attributes?

后端 未结 4 1942
名媛妹妹
名媛妹妹 2021-02-05 04:51

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

@model MVCApp.ViewModels.TitlesViewModel

<         


        
相关标签:
4条回答
  • 2021-02-05 04:58

    Here is what you need to do.

    id="label_@Model.Id"
    

    Underscore(_) is required.For me passing id without Underscore made an issue. Happy conding.

    0 讨论(0)
  • 2021-02-05 05:04

    Try this (verified):

    <div id="@("label"+Model.Id)" class="display-field">@Model.InitValue</div>
    
    0 讨论(0)
  • 2021-02-05 05:10

    You want:

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

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

    Edit:

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

    <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)" />
    

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

    0 讨论(0)
  • 2021-02-05 05:11

    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(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()) })
    
    0 讨论(0)
提交回复
热议问题