2011-05-31 85 views
2

我試圖在我的web應用程序中使用雅虎富文本編輯器。我對網絡編程很陌生,所以這可能是一個愚蠢的問題。如何發佈JavaScript變量到ASP.net MVC模型?

我正在使用名爲「blogpost」的自定義模型。它包含以下屬性:

標題 身體 dateCreated會 作者

我想使用的自定義編輯器只對「身體」屬性。當我點擊提交時,它將從簡單的文本框構建模型的其他屬性。我已經將下面的代碼放在我的輸入表單代碼中。

<div class="yui-skin-sam"> 
     <textarea name= "msgpost" id="msgpost" cols="50" rows="10"> 
     </textarea> 
     <script> 

      var myEditor = new YAHOO.widget.Editor('msgpost', { 
      height: '300px', 
      width: '522px', 
      dompath: true, //Turns on the bar at the bottom 
      animate: true //Animates the opening, closing and moving of Editor windows 
      }); 

      myEditor.render(); 

      YAHOO.util.Event.on('Create', 'click', function() { 
       myEditor.saveHTML(); 
       var body = myEditor.get('element').value; 

      });        
     </script> 
     @ViewData.Add("Body",//how do I add the javascript variable "body" ?) 


</div> 

如何「發佈」javascript變量「body」,以便MVC模型構建器能夠識別它?

回答

2

你不能在你的MVC視圖中這樣做。你需要用javascript來完成。

您需要在窗體上掛接Submit事件,然後在編輯器中獲取文本的值,並將其添加到發佈數據中。喜歡的東西:

$('form').submit(function(event){ 
    // cancel the default action 
    event.preventDefault(); 
    var body = escape(myEditor.get('element').value); 

    var theForm = $(this); 
    $.post(theForm.attr('action'), theForm.serialize() + '&body=' + body, function (data) { 
     // do whatever with the result 
    }); 
}); 

另一種方式來做到這將是一個隱藏字段添加到您的形式和更新字段編輯器的值:

<input id="body" name="body" type="hidden" value=""/> 

然後設置而不是body變量你可以這樣做:

YAHOO.util.Event.on('Create', 'click', function() { 
    myEditor.saveHTML(); 
    $('#body').attr('value', myEditor.get('element').value); 
}); 

然後數據是在窗體中,窗體將處理其餘的。

+0

採取了第二個途徑。謝謝! – ZeroDivide 2011-05-31 05:58:19

0

編寫一些javascript以將編輯器內容保存到隱藏的輸入中,並將其與表單一起發佈。然後,您將能夠使用editorBodyText作爲字符串參數訪問MVC控制器操作中的內容。

例如Javascript和HTML:

<script type="text/javascript" > 
    $(document).ready(
     function() { 
      $("#submitButton").click( 
       function(){ 
         $("#editorBodyText").val(myEditor.get('element').value); 
       } 
      ); 
     } 
    ); 
</script> 

<input id="editorBodyText" name="editorBodyText" type="hidden" value=""/> 
<input id="submitButton" type="submit" value="save" /> 

MVC控制器:

public ActionResult HandlePost(string editorBodyText){ 
//TODO: process your data here e.g. save to DB. 
} 
相關問題