Custom rendering logic on server side + MVC + Ajax
I have some rendering logic for custom markup (a'la bbcode, but not bbcode). So that when I'm getting the stuff from DB I'm then calling MyRender.ToHTML(model.text)...
Now what I do today is I just have a form below and I do a post and add the item and return the same view. My question is - how to do it with ajax? Should I create a control and return HTM开发者_如何学JAVAL a'la winforms? Is that sexy? How do you do something like that? Or should I drop it? Maybe duplicate the rendering logic with javascript?
Using jQuery is the easiest way to accomplish this. The way that would work with an MVC:
1 => Catch the form submit with jQuery
$('#id_of_form').submit(function() {
// do stuff
// at the end, prevent the normal submit
return false;
});
2 => Send the form data to your Controller, e.g.:
// do stuff
$.post('your_controller.asp', $(this).serialize(), function(data) {
// do stuff with the returned data
});
More info on how this works: http://api.jquery.com/jQuery.post/
3 => In your Controller you see that the form is submitted, and you send the data to the Model where it gets processed. Then the Controller takes the submitted text with the bb-like-code and formats it. After that you echo/display the formatted text.
Everything that's being returned after calling your_controller.asp
(in this case that should be the formatted text) will be stored in the variable data
. You can then use that data and tell jQuery to add it to the page in a specific element (e.g. a div
below the form that shows what you posted):
// do stuff with the returned data
$('#id_of_result_element').html(data);
精彩评论