simplest way to post post data from mvc dialog to

2019-09-03 16:52发布

问题:

How can I send data from a dialog to the controller? Model Binding?

Can I have example please?

回答1:

I'm making some assumptions here based on your previous questions that you are interested in ASP.NET MVC and are using jQuery UI dialogs. Further I'm guessing that you want the data submitted without reloading the page -- i.e., the dialog should be dismissed and return you back to the original page.

The simplest way is to create a form in the dialog and have that form submited via AJAX. I would suggest that you have the dialog populated via a controller action that loads a partial view. This will make it simpler to generate the mark up for the dialog. Give the content area of the dialog a class that makes it easy to find once the dialog is created, then in the dialog open handler replace the HTML inside the content area via a load to the controller action. Use the buttons on the dialog to submit the form.

 $(function() {
    $('.someSelector').click( function() {
        $('<div title="Update Contacts"><p class="dialog-content"></p></div>').dialog({
            autoOpen: true,
            modal: true,
            open: function() {
                 $(this).find('.dialog-content')
                        .load( '<%= Url.Action( "show", "contact", new { id = Model.UserID } ) %>',
                              function() {
                                 $(this).find('form').submit( function() {
                                       return false;
                                 }
                              }
                         );
            }
            buttons: function() {
                'Update': function() {
                             var $this = $(this);
                             var form = $this.find('form');
                             $.post( form.attr('action'), form.serialize(), function(){
                                   $this.dialog('destroy');
                             });
                           },
                'Cancel': function() {
                             $(this).dialog('destroy');
                          }       
            }
        });
    });
});

Partial view

<% using (Html.BeginForm( "update", "contact", null, FormMethod.Post, new { id = "contact-form" } )) { %>
   <%= Html.EditorForModel() %>
<% } %>