iT邦幫忙

0

如何定義一個字串變數 包含字串與html tag 印出後可保有html tag的效果

目前在寫MVC的View,如下簡單敘述問題,主要是希望透過傳入一個變數,可以印出呈現html tag效果的文字,但以下寫法會將html tag也視為字串內容印出,而不會呈現文字+文字下標的效果,請問要怎麼調整呢?

@helper GetResult(string title, string content){
    <div class='div_table'>
        <div class='div_tr'>
            <div class='div_td'>
                @title
            </div>
            <div class='div_td'>
                @content
            </div>
        </div>
    </div>
}
<div>
    @GetResult("title1", "content<span style='font-size:6px;'><sub>something else</sub></span>")
</div>
黃彥儒 iT邦高手 1 級 ‧ 2019-09-09 16:35:28 檢舉
使用模版
anniecat iT邦新手 3 級 ‧ 2019-09-09 16:44:03 檢舉
Hi 黃彥儒 , 不好意思...請問您說的模板是什麼呢?
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
YoChen
iT邦研究生 1 級 ‧ 2019-09-09 16:48:41
最佳解答

您可以參考方法HtmlHelper.Raw

<div class='div_table'>
    <div class='div_tr'>
        <div class='div_td'>
            @Html.Raw(title)
        </div>
        <div class='div_td'>
            @Html.Raw(content)
        </div>
    </div>
</div>

官方文件
https://docs.microsoft.com/zh-tw/dotnet/api/system.web.mvc.htmlhelper.raw?view=aspnet-mvc-5.2

看更多先前的回應...收起先前的回應...
YoChen iT邦研究生 1 級 ‧ 2019-09-09 16:54:18 檢舉

抱歉,我邏輯看反了,依照您的程式,應該是這樣~XDDD

<div>
    @Html.Raw(GetResult("title1", "content<span style='font-size:6px;'><sub>something else</sub></span>"))
</div>
anniecat iT邦新手 3 級 ‧ 2019-09-09 18:52:00 檢舉

YoChen,謝謝您的幫忙,之前有使用過這個方法,但熊熊忘記XD
兩種方式都有嘗試,但發現還是會直接印出包含html tag的字串...我也再往這個方向研究看看!

YoChen iT邦研究生 1 級 ‧ 2019-09-10 09:44:53 檢舉

或是您也可以使用HtmlString試試看~

<div>
    @(new HtmlString(GetResult("title1", "content<span style='font-size:6px;'><sub>something else</sub></span>").ToString()))
</div>
anniecat iT邦新手 3 級 ‧ 2019-09-10 13:26:55 檢舉

謝謝YoChen的幫忙~上網查詢了兩者的差異,發現結果應該要一樣的,於是重新嘗試您提供的方法,結果是可行的,應該是昨天網頁catch住,因此沒有正確顯示結果...不好意思麻煩您了,也懂更多了!再次感謝您!

YoChen iT邦研究生 1 級 ‧ 2019-09-10 13:47:59 檢舉

我剛剛有幫您稍微試了一下,要記得在您自訂的function內也必須用Html.Rawnew HtmlString輸出才行哦~

@helper GetResult(string title, string content)
{
    <div class='div_table'>
        <div class='div_tr'>
            <div class='div_td'>
                @Html.Raw(title) // 擇一
                @(new HtmlString(title)) // 擇一
            </div>
            <div class='div_td'>
                @Html.Raw(content) // 擇一
                @(new HtmlString(content)) // 擇一
            </div>
        </div>
    </div>
}

使用function的地方

<div>
    @(Html.Raw(GetResult("title1", "content<span style='font-size:6px;'><sub>something else</sub></span>"))) // 擇一
    @(new HtmlString(GetResult("title1", "content<span style='font-size:6px;'><sub>something else</sub></span>").ToString())) // 擇一
</div>

不過我自己在寫作的時候還是比較偏好把靜態的Html Tag直接寫在頁面上,有需要動態顯示的內容才使用function來幫助處理,以上供您參考~

anniecat iT邦新手 3 級 ‧ 2019-09-10 14:32:12 檢舉

好的!瞭解了~再次感謝您~~

我要發表回答

立即登入回答