doogdeb
doogdeb

Reputation: 403

MVC3 Razor concatenation issue

I am trying to create an id for an input by doing the following

    id="@ViewData.ModelMetadata.ContainerType.Name + "_" +  @ViewData.TemplateInfo.GetFullHtmlFieldId("FromDate")"

but it is coming through with id="propertyName +". How can I concatenate the two together with an underscore in the middle in a razor view?

Upvotes: 2

Views: 1057

Answers (3)

João Angelo
João Angelo

Reputation: 57718

You can use the @(expression) syntax to express an explicit code expression.

You need to be explicit here because the space after @ViewData.ModelMetadata.ContainerType.Name is not a valid character for a C# identifier so the evalutation stops there.

The algorithm used by Razor for processing implicit code expression is the following:

  1. Parse an identifier - As soon as we see a character that isn't valid in a C# or VB identifier, we stop and move to step 2
  2. Check for brackets - If we see "(" or "[", go to step 2.1., otherwise, go to step 3
    1. Parse until the matching ")" or "]" (we track nested "()" and "[]" pairs and ignore "()[]" we see in strings or comments)
    2. Go back to step 2
  3. Check for a "." - If we see one, go to step 3.1, otherwise, DO NOT ACCEPT THE "." as code, and go to step 4
    1. If the character AFTER the "." is a valid identifier, accept the "." and go back to step 1, otherwise, go to step 4
  4. Done!

(Taken from ScottGu's Blog)

Upvotes: 4

DanielB
DanielB

Reputation: 20230

id="@(ViewData.ModelMetadata.ContainerType.Name + "_" +  ViewData.TemplateInfo.GetFullHtmlFieldId("FromDate"))"

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039408

Try like this:

id="@(ViewData.ModelMetadata.ContainerType.Name)_@(ViewData.TemplateInfo.GetFullHtmlFieldId("FromDate"))"

or like this:

id="@string.Format("{0}_{1}", ViewData.ModelMetadata.ContainerType.Name, ViewData.TemplateInfo.GetFullHtmlFieldId("FromDate"))"

Upvotes: 3

Related Questions