如何将javascript变量发布到ASP.net MVC模型?

我试图在我的Web应用程序中使用Yahoo富文本编辑器。 我对网络编程有点新意,所以这可能是一个愚蠢的问题。

我正在使用名为“blogpost”的自定义模型。 它包含以下属性:

标题正文DateCreated作者

我想只为“body”属性使用自定义编辑器。 当我单击提交时,它将从简单的文本框构建模型的其他属性。 我已经使用输入表单代码放置了以下代码。

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; }); @ViewData.Add("Body",//how do I add the javascript variable "body" ?)

如何“发布”javascript变量“body”,以便MVC模型构建器识别它?

您无法在MVC视图中执行此操作。 你需要在javascript中完成它。

您需要在表单上挂钩Submit事件,然后在编辑器中获取文本的值,并将其添加到post数据中。 就像是:

 $('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 }); }); 

另一种方法是在表单中添加一个隐藏字段,并使用编辑器的值更新该字段:

  

然后,您可以执行以下操作,而不是设置body变量:

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

然后数据在表单中,表单将处理其余的。

编写一些javascript来将编辑器内容保存到隐藏的输入中并使用表单发布。 然后,您将能够使用editorBodyText作为字符串参数访问MVC控制器操作中的内容。

例如Javascript和HTML:

    

MVC控制器:

 public ActionResult HandlePost(string editorBodyText){ //TODO: process your data here eg save to DB. }