2011-07-12 92 views
20

我使用MVC3,我想用一個局部視圖創建動態DOM元素。這是我目前的局部視圖:有沒有辦法在html屬性中連接字符串?

@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)爲此事)認可的一個相干串。

回答

44

試試這個(認證) 。我需要使用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()) }) 
+0

這工作:''

@Model.InitValue
非常感謝。 – user558594

+2

加引號剛纔(而你可以發佈您的評論):) – Mrchief

+0

是啊,我看到了。不過,感謝您的幫助。我仍然是MVC3和Razor語法的新手。 – user558594

2

你想:

<div id="[email protected]" ... 

剃刀將承認@作爲代碼的開始,執行它並呈現在屬性到位的結果。

編輯:

這並沒有和評論工作,但這裏是從我的剃鬚刀控件之一線:

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

嘗試增加一個連字符( - )@前面。 Razor很可能認爲這是一個電子郵件地址,並且一個人留下!試圖Concat的字符串和型號值作爲ID在@ html.ActionLink,也爲文本值時

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

我試過了。在我的瀏覽器的HTML源代碼中,ID是簡單的「[email protected]」 – user558594

1

只是添加另一種選擇,因爲這是對我工作:

相關問題