问题
Im trying to use the Yahoo rich text editor in my web application. I'm kind of new to web programming so this may be a silly question.
I'm using a custom model called "blogpost". It contains the following properties:
Title Body DateCreated Author
I want to use the custom editor for only the "body" property. When I click submit it will build the other properties of the model from simple textboxes. I have placed the following code withing my input form code.
<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>
How do I "post" the javascript variable "body" so the MVC model builder recognizes it?
回答1:
You can't do this in your MVC View. You need to do it in javascript.
You'll need to hook the Submit event on the form and then get the value of the text in the editor, and add it to the post data. Something like:
$('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
});
});
Another way to do it would be to add a hidden field to your form and update that field with the value of the editor:
<input id="body" name="body" type="hidden" value=""/>
then instead of setting the body
variable you can do this:
YAHOO.util.Event.on('Create', 'click', function () {
myEditor.saveHTML();
$('#body').attr('value', myEditor.get('element').value);
});
Then the data is in the form and the form will handle the rest.
回答2:
Write some javascript to save the editor contents into a hidden input and post that with the form. You will then be able to access the content in the MVC controller action using editorBodyText as a string parameter.
E.g. Javascript and 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 Controller:
public ActionResult HandlePost(string editorBodyText){
//TODO: process your data here e.g. save to DB.
}
来源:https://stackoverflow.com/questions/6181822/how-do-i-post-a-javascript-variable-to-an-asp-net-mvc-model