Ajax Post后重新加载页面

时间:2014-05-14 08:32:16

标签: javascript jquery ajax asp.net-mvc json

我正在使用asp.net MVC

进行单页应用程序

当我从Ajax发布到服务器时,Web API验证发送的参数,然后返回Json字符串。这是我的Web API中的功能

Public Class VerifyReturn
    Public SerBool As String
    Public SerMessage As String
    Public TextBool As String
    Public TextMessage As String
End Class

<HttpPost>
Public Function ValidateParam(ByVal ser As Integer, ByVal content As String) As List(Of VerifyReturn)
    Dim ErrorsJson As String = ""
    Dim Errors As Boolean = False


    Try
        If Not ser = Nothing AndAlso IsNumeric(ser) = True Then  
            ErrorsJson &= "[{""SerBool"":""0"",""SerMessage"":"""","
        Else
            ErrorsJson &= "[{""SerBool"":""1"",""SerMessage"":""Not Valid."","
            Errors = True
        End If

       If Not content Is Nothing AndAlso content.Length < 151 Then
            ErrorsJson &= """TextBool"":""0"",""TextMessage"":""""}]"
       Else
            ErrorsJson &= """TextBool"":""1"",""TextMessage"":""Content Too Large.""}]"
            Errors = True
        End If

        Dim ReturnJson = JsonConvert.DeserializeObject(Of List(Of VerifyReturn))(ErrorsJson)
        Return ReturnJson


    Catch ex As Exception

    End Try
End Function

这是我的Ajax:

 $(document).ready(function () {
      $('#BtnInsert').click(function () {

           $.ajax({
                    url: '@Url.Content("~/api/ContentM/ValidateParam?ser=")' + $('#SerList').val() + ("&content=") + $('#TxtContent').val(),
                    type: 'POST',
                    success: function (responseData) {
                        for (var i = 0; i < responseData.length; i++) {

                            If(responseData[i].TextBool == '1')
                            {
                                $('#LblErrors').val(responseData[i].TextMessage);
                            }
                        }
                    }
                });
          });
      });

正在触发API功能,服务器端程序正常,

但是当ajax调用完成后,页面重新加载,我在$(&#39;#LblErrors&#39;)标签中看不到任何内容。

我做错了什么?

2 个答案:

答案 0 :(得分:1)

如果我没弄错,在HTML上使用<button></button>,表单会自动提交。那可能是你的问题。解决问题的一种方法是按照我们的朋友上面说的return false。所以它应该是这样的:<button id="BtnInsert" onclick="return false">Insert</button>。另一种方法是阻止使用.click(function(e)

e.preventDefault()函数中自动提交

答案 1 :(得分:0)

试试这个:

$(document).ready(function () {
  $('#BtnInsert').click(function (e) {
       e.preventDefault();

       $.ajax({
                url: '@Url.Content("~/api/ContentM/ValidateParam?ser=")' + $('#SerList').val() + ("&content=") + $('#TxtContent').val(),
                type: 'POST',
                success: function (responseData) {
                    for (var i = 0; i < responseData.length; i++) {

                        If(responseData[i].TextBool == '1')
                        {
                            $('#LblErrors').val(responseData[i].TextMessage);
                        }
                    }
                }
            });
      });
  });