如何解决如何将JavaScript变量发布到ASP.net MVC模型?
| 我试图在我的Web应用程序中使用Yahoo RTF编辑器。我是Web编程的新手,所以这可能是一个愚蠢的问题。 我正在使用一个名为\“ blogpost \”的自定义模型。它包含以下属性: 标题 身体 创建日期 作者 我只想将自定义编辑器用于\“ body \”属性。当我单击提交时,它将通过简单的文本框构建模型的其他属性。我在输入表单代码中放置了以下代码。<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模型构建器可以识别它?
解决方法
您无法在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=\"\"/>
然后您可以执行以下操作,而不是设置ѭ3this变量:
YAHOO.util.Event.on(\'Create\',\'click\',function () {
myEditor.saveHTML();
$(\'#body\').attr(\'value\',myEditor.get(\'element\').value);
});
然后数据就在表格中,表格将处理其余部分。
, 编写一些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.
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。