2012-10-06 5 views
3
@using(Html.BeginForm("About", "User", FormMethod.Post , new { id="aboutme"})) 
{ 
    <fieldset> 
      <ul> 
      <li> <label class="block">About me</label> @Html.TextAreaFor(m=>m.About.AboutMe)</li> 
      <li> <input type="button" id="submit" class="input-button" /> </li> 
      </ul> 
    </fieldset> 
} 

<script type="text/javascript"> 
    $(function() { 
     $('#submit').click(function() { 

      $.ajax({ 
       url: this.action, 
       type: this.method, 
       data: $(this).serialize(), 
       success: function (result) { 
        // The AJAX call succeeded and the server returned a JSON 
        // with a property "s" => we can use this property 
        // and set the html of the target div 
        alert(result.s); 
        $('#ShowResultHere').html(result.s); 
       } 
      }); 
      // it is important to return false in order to 
      // cancel the default submission of the form 
      // and perform the AJAX call 
      return false; 
     }); 
    }); 
</script> 

Lorsque je débogue, l'URL d'action devient /User/undefined.MVC 4 Ajax Post ne fonctionne pas

Comment puis-je résoudre ce problème?

Répondre

4

Le mot-clé this fait référence à la source de l'événement, qui est le bouton submit dans ce cas. Vous voulez la forme, donc essayez ceci (en utilisant JQuery traversing):

url: $(this).closest("form").prop("action"), 
type: $(this).closest("form").prop("method"), 
data: $(this).closest("form").serialize() 

L'alternative serait d'utiliser <input type='submit' class='input-button' /> au lieu du button, et écouter l'événement $("#aboutme").submit (cette façon this aurait fait référence à la forme, comme votre code suppose).

+0

ouais je figuré. Merci. – DarthVader

1

En fonction attr alternative pour obtenir la valeur de l'attribut http://api.jquery.com/attr/ et aussi, jQuery a un raccourci pour le post ajax, .post $ http://api.jquery.com/jQuery.post/ de sorte que votre code pourrait finir comme ce

$("#submit").click(function(event){ 
    event.preventDefault(); 
    $.post($("#aboutme").attr("action"), $("#aboutme").serialize(), function (data) { 
     if (data != null) { 
      alert(result.s); 
      $('#ShowResultHere').html(result.s); 
     } 
    }); 
}); 
+0

merci. Je l'ai déjà fait. Merci quand même:) – DarthVader