2013年10月24日 星期四

Asp.net MVC 實作TinyMCE文字編輯器搭配@Html.Raw(3)

先廢話一下
昨天在想目前常接到需要文字編輯器的網頁程式
之前都是使用CkEditor但在MVC上不是很好套
所以找了一款我個人覺得蠻合適的編輯器TinyMCE
就看個人的需求來選擇
套用方式很簡單form部份如下
如果是強型別可改為@Html.TextAreaFor
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        @Html.TextArea("abc")
        <input type="submit" value="送出" />
    }
再加入參考js及寫script
<!--http://www.tinymce.com/i18n/-->
<!--http://www.tinymce.com/tryit/classic.php-->
<script src="~/Scripts/tinymce/tinymce.min.js"></script>
<script>
  tinymce.init({
    selector: 'textarea', //設定那一個標籤會用
    language: "zh_tw", //語言
    plugins: [
      "advlist autolink autosave link image lists charmap print preview hr anchor pagebreak spellchecker",
      "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
      "table contextmenu directionality emoticons template textcolor paste fullpage textcolor"
    ],//設定須要那些外掛
    toolbar1: "newdocument fullpage | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | styleselect formatselect fontselect fontsizeselect",
    toolbar2: "cut copy paste | searchreplace | bullist numlist | outdent indent blockquote | undo redo | link unlink anchor image media code | inserttime preview | forecolor backcolor",
    toolbar3: "table | hr removeformat | subscript superscript | charmap emoticons | print fullscreen | ltr rtl | spellchecker | visualchars visualblocks nonbreaking template pagebreak restoredraft",
    toolbar_items_size: 'small'//小圖的ToolBar
    });
</script>
在action裡接收程式碼如下
當然也可以使用強型別接會更會
記得加[ValidateInput(false)]
不然會出現"具有潛在危險"Request.Form 的值已從用戶端"
但最好使用時要小心最後是在後台有權限判斷才能使用
[HttpPost]
[ValidateInput(false)]
public ActionResult Index(FormCollection form)
{
  if(ModelState.IsValid)
  {
    string test = form["abc"];
  }
    return View();
}

2013-10-29補充
使用文字編輯器時通常為在前後產生
<p></p>
而在MVC中如果是以欄位
@item.content
來輸出裡面有

則會備程式編成html 所以需搭配

@Html.Raw(@item.content)