Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With ASP.NET MVC, what is the preferred way to Ajaxify a simple form?

I am trying to add a simple comments/message box to a web page. When the user enters the comment and hits submit, I would like to save this message to the database and add the comment to the list displayed on the page, without refreshing the entire page.

However, I am not sure of the best way to do that these days. I am using ASP.NET MVC 2. I have been trying to read up on using JQuery for this type of functionality, but I am having problems getting a full picture of the correct approach that isn't also out of date (i.e. it is using an preview version of MVC 1 or older version of JQuery).

I can either find snippets of different pieces without the information of how they work together, or the information appears to be quite dated and no longer valid.

Can someone point me in the right direction for something like this?

Ideally, I am looking for a simple example of the JQuery code, a snippet of any key differences in an HTML form from a normal post method, and the basic method used in the MVC Controller. I need something to help the lightbulb of understanding to turn on. :)

Any help would be greatly appreciated!!

like image 582
Swoop Avatar asked May 18 '10 19:05

Swoop


2 Answers

I usually do something like

<form action="/controller/action" method="post" id="formID">
</form>

$("#formID").submit(function(){
  var form = $(this);
  $.post(form.attr("href"), form.serialize(), function(data){/*manipulate page*/}, "text")
  return false;
});

The MVC controller is just like it would be if you weren't using Ajax, except you probably return a different view--one that doesn't contain a full page of markup, depending on what data you want to get from the server. You might not need to return any data at all--your "manipulate page" code might have all the info it needs already.

like image 136
joelt Avatar answered Oct 05 '22 21:10

joelt


You should check out the jQuery Form plugin. You can POST the comment to your controller with ajax, persist the comment, and return a bool w/ JSON. In jquery, define a success handler (see the examples tab) and render the comment at the bottom of your page. You can also check out javascript templates (here is Microsoft's proposed implementation) if you want some formatting control over how to render the comment (without cluttering your JS).

like image 38
Ryan Avatar answered Oct 05 '22 19:10

Ryan