Reputation: 3185
I am doing a Single Page Application using asp.net MVC
When I'm posting to the server from Ajax, The Web API validates the parameters sent, then returns a Json String. Here's the function in my 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
This is my 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);
}
}
}
});
});
});
The API function is being triggered and the procedure server side is going fine,
But when the ajax call finishes, the page reloads and I see nothing in my $('#LblErrors') Label.
What am I doing wrong?
Upvotes: 1
Views: 139
Reputation: 1042
If I'm not mistaken, using <button></button>
on HTML, a form is submitted automatically. That might be your problem. One way to solve it is putting a return false
as our friend said above. So this is how it should be: <button id="BtnInsert" onclick="return false">Insert</button>
. Another way is preventing the automatic submitting inside your .click(function(e)
function using e.preventDefault()
Upvotes: 1
Reputation: 146
Try this:
$(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);
}
}
}
});
});
});
Upvotes: 0