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).
HTML is a markup language. No, it has no 'concatenation functionality'.
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.
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.
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.
Try this (verified):
<div id="@("label"+Model.Id)" class="display-field">@Model.InitValue</div>
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With