2012-10-06 144 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> 

當我調試這個時,動作URL變成/User/undefinedMVC 4 Ajax發佈不起作用

我該如何解決?

回答

4

this關鍵字是指事件的來源,在這種情況下是submit按鈕。你想要的形式,讓試試這個(使用JQuery traversing):

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

另一種方法是使用<input type='submit' class='input-button' />代替button,並監聽的事件$("#aboutme").submit(這樣this居然會指形式,如你的代碼假定)。

+0

是的,我想通了。謝謝。 – DarthVader

1

作爲替代ATTR功能,獲取屬性 http://api.jquery.com/attr/ 也值,jQuery有阿賈克斯後的簡寫,$。員額 http://api.jquery.com/jQuery.post/ 讓你的代碼可以結束!這

$("#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

謝謝。我已經完成了。不管怎麼說,多謝拉:) – DarthVader