asp.net mvc - How to make a .NET MVC Form inside a Modal using jQuery with validation -


i struggling knowing how put together. i've built forms inside .net mvc pages plenty of times, , without validation. , i've built forms using jquery, , without validation. , i've built forms inside of modal, never mvc.

i understand original question because form inside modal i'll need use jquery handle submit. having heck of time figuring out how put these moving pieces together. far, i've not found tutorial (or combo of tutorials) puts together.

here's need:

  • inside of mvc view, there button opens modal. (this working fine.)
  • once modal opens, contains form several text fields , dropdowns. each required. (to make fields required, define these in view's model, mvc form? or create requirements in jquery?)
  • if user attempts submit form , empty or invalid, modal stays open , validation messages appear. (i understand, original question, not possible using straight mvc because of modal, , jquery needed. i'm lost here.)
  • if user attempts submit form , fields valid, modal closes, hit controller , save fields db. (not sure how escape out of jquery , hit normal controller handle final logic.)

edit:

thank you, jason, help! based on suggestions, how got working.

the parent view:

the modal:

<div class="modal fade" id="accounteditmodal" tabindex="-1" role="dialog" aria-labelledby="accounteditmodallabel">     <div class="modal-dialog modalaccountedit" role="document">         <div class="modal-content">             <div class="modal-header">                 <button type="button" class="close" data-dismiss="modal" aria-label="close"><span aria-hidden="true">&times;</span></button>                 <h3><strong>edit account profile - <span class="accountname"></span></strong></h3>             </div>              <div class="modal-body">                 <div id="formcontant">                     @html.partial("_accountprofileedit", new gedcpatientportal.models.accountprofileeditviewmodel())                 </div>             </div>         </div>     </div> </div> 

and here's scripts:

@section scripts {     <script>         $(document).ready(function () {              $('#accounteditmodal').on('shown.bs.modal', function () {                 $('#myinput').focus()             })            $("#accounteditmodal").on("submit", "#form-accountprofileedit", function (e) {             e.preventdefault();  // prevent standard form submission              var form = $(this);             $.ajax({                 url: form.attr("action"),                 method: form.attr("method"),  // post                 data: form.serialize(),                 success: function (partialresult) {                     $("#formcontent").html(partialresult);                 }             });         });           });      </script> } 

the partial view (slimmed down):

@using (html.beginform("accountprofileedit", "account", formmethod.post, new { id = "form-accountprofileedit", @class = "full-form" }))     {       @html.customtextboxfor(model => model.address)       <div style="text-align:right;">         <button type="submit" id="accountprofileedit-submit" name="accountprofileedit-submit" value="edit account" class="btn btn-primary" style="margin-left:5px;">edit account</button>         <button type="button" class="btn btn-primary" data-dismiss="modal">cancel</button>     </div> } 

the controller:

    [httppost]     public actionresult accountprofileedit(accountprofileeditviewmodel model)     {         if (modelstate.isvalid)         {             // logic store form data in db         }          return partialview("_accountprofileedit", model);      } 

you can use built-in mvc validation scripts along data annotaions on model

public class accountprofileeditviewmodel {     [display(name = "address")]     [required()]     [stringlength(200)]     public string address { get; set; } } 

make partial view hold modal form.

_accountprofileedit.cshtml

@model accountprofileeditviewmodel  @using(html.beginform("accountprofileedit", "account",            formmethod.post, new { id = "form-accountedit-appt" }) {     @html.validationsummary(true)      @html.labelfor(m => m.address)     @html.textboxfor(m => m.address)     @html.validationmessagefor(m => m.address)     <button type="submit">edit</button> } 

then reference in modal box. if want pre-populated model you'll need render action:

<div class="modal-body" id="form-container">     @html.action("accountprofileedit", "account", new { id=account.id }) </div> 

if want blank form can use:

<div class="modal-body" id="form-container">     @html.partial("_accountprofileedit") </div> 

the action uses id parameter fetch , populate model

[httpget] public actionresult accountprofileedit(int id) {     accountprofileeditviewmodel model = db.getaccount(id);  // in app      return partialview("_accountprofileedit", model); } 

ajax post

now you'll need ajax submit form. if rely on standard form submission browser navigate away page (and close modal).

$("#mymodal").on("submit", "#form-accountedit", function(e) {     e.preventdefault();  // prevent standard form submission      var form = $(this);     $.ajax({         url: form.attr("action"),         method: form.attr("method"),  // post         data: form.serialize(),         success: function(partialresult) {             $("#form-container").html(partialresult);         }     }); }); 

you need use event delegate $(staticparent).on(event, target, handler) submit event because form content may replaced later.

post action

[httppost] public actionresult accountprofileedit(accountprofileeditviewmodel model) {     // request.form model      if (modelstate.isvalid)     {         // work         return partialview("_accounteditsuccess");     }      return partialview("_accountprofileedit", model); } 

client-side validation scripts should prevent them ever submitting. if somehow failed or if can't validate on client have modelstate.isvalid. might invalidate server-side manually.

_accounteditsuccess.cshtml

and "success" partial view.

<div>success! <button>click close</button></div> 

not valid fail, right?

from ajax success handler have

success: function(partialresult) {     $("#form-container").html(partialresult); } 

but problem here don't know if getting "success" or "validation failure". adding error: function(err){ } handler won't because validation failure considered http 200 response. in both cases div content replaced user need manually close modal. there are ways pass additional data distinguish both conditions that's long answer post.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -