views:

250

answers:

3

I have a Jquery modal dialog, My question is what is the best way to send this data to the controller, and to display a message back to the dialog. I can not seem to find and good examples of this.

+1  A: 

With JQuery, you can get the Form plugin, and submit your form easily with Ajax like this:

 $('#myform').ajaxForm({
      url: '/mycontroller/myaction/myid',
      datatype: 'json',
      success: function(responseJson) { 
                    alert ('success! response was:' + responseJson); 
               }
   });
womp
how would I do this without the plugin?
Tony Borf
A: 
$.post('site/controller/action', $('#myForm').serialize(), function (data) {
    alert('form submitted');
}, 'json');
RaYell
A: 

Put data collection controls within a form like so:

Task ID

Level: Major ID: Minor ID:

Description:

ResponsibleRole:

DurationInDays:

Task Type:

Next add the following Javascript: Note Open function Add has a Serialize. This assembles the Json data. Now go down and look at the DTO then the controller.

AddTaskHandler = function() { var SuccessHandler; /* Open the dialog */ Open = function(successHandler, projectId, templateName) { SuccessHandler = successHandler; $('#AddTaskProjectId').val(projectId); $('#AddTaskTemplateName').val(templateName); $('#AddTaskDiv').dialog('open'); } /* Initialize the add Task Dialog */ Init = function() { $('#AddTaskDiv').dialog({ autoOpen: false, modal: true, height: 400, width: 535, buttons: { Cancel: function() { $(this).dialog("close"); }, Add: function() { var mydialog = $(this); var formData = $('#AddTaskForm').serializeArray(); $.post("/Template/AddTask", formData, function(data) { if (data.Status == false) { alert(data.Message); } else { SuccessHandler(data); mydialog.dialog("close"); } }, "json"); } } }); }; return { Init: Init, Open: Open }; } (); $(document).ready(function() { AddTaskHandler.Init(); });

Create a DTO: Note property names ar identical to form control names:

public class TaskDto { public string AddTaskProjectId { get; set; } public string AddTaskDescription { get; set; } public string AddTaskDurationInDays { get; set; } public string AddTaskLevel { get; set; } public string AddTaskTemplateId { get; set; } public string AddTaskTemplateName { get; set; } public string AddTaskMajorLevel { get; set; } public string AddTaskMinorLevel { get; set; } public string AddTaskResponsibleRole { get; set; } public string AddTaskActive { get; set; } public string AddTaskType { get; set; } }

Your MVC controller:

    public ActionResult AddTask(TaskDto taskDto)
    {

         Code here
    }

And thats it.

So I place the dialog in my site master making it there all the time, ready. It initializes itself.

Then when I need it I call the open and then rest is done.