2012-10-06 3 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/undefined이됩니다.MVC 4 Ajax 포스트 작동하지 않음

어떻게 해결할 수 있습니까?

답변

4

this 키워드는 이벤트 소스 (이 경우 submit 버튼)를 나타냅니다. 당신은 (JQuery traversing 사용) 양식을 원하므로이 시도 :

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

대안으로 대신 button<input type='submit' class='input-button' />를 사용하고 이벤트 $("#aboutme").submit (this 실제로 양식을 참조 할 그런 식으로 수신하는 것 귀하의 코드가 가정합니다).

+0

예. 감사. 덕분에 – DarthVader

0

대신 Ajax.BeginForm 메소드를 사용할 수 있습니다.이 메소드를 사용하면 반환 된 모든 HTML에 대한 업데이트 대상을 설정할 수 있습니다. 예

: 대안 ATTR 기능으로 Using Ajax.BeginForm with ASP.NET MVC 3 Razor

1

http://api.jquery.com/attr/ 또한 속성의 값을 얻기 위해, jQuery를 아약스의 게시물에 대한 속기, $ .post 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

관련 문제