Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to concatenate strings in html attributes?

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  <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:

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).

like image 738
user558594 Avatar asked Jul 12 '11 21:07

user558594


People also ask

Can you concatenate strings in HTML?

HTML is a markup language. No, it has no 'concatenation functionality'.

Which operator is used to concatenate two strings HTML?

The ampersand symbol is the recommended concatenation operator. It is used to bind a number of string variables together, creating one string from two or more individual strings.

How do I combine two string values?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

How do I combine all strings into one string?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.


2 Answers

Try this (verified):

<div id="@("label"+Model.Id)" class="display-field">@Model.InitValue</div> 
like image 59
Mrchief Avatar answered Oct 05 '22 07:10

Mrchief


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.

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 [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!

like image 33
Steve Morgan Avatar answered Oct 05 '22 07:10

Steve Morgan