Calling vb code-behind function from ajax-call - ajax

I try to call a shared vb function from markup with ajax-call but it doesn't return the string, it returns the markup of the whole page.
ajax-call from button #apply in file philipp.aspx
jQuery("#apply").click(function () {
jQuery.ajax({
type: "GET",
url: "philipp.aspx/Test",
dataType: "text",
success: function (data) {
console.log(data + " Successful")
},
error: function (data) {
console.log(data.status + " Not Successful")
}
});
});
vb code-behind in philipp.aspx.vb
Imports System.Web.Services
Imports System.Web.Script.Services
<ScriptService()>
Partial Public Class PhilippPage
Inherits System.Web.UI.Page
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
<WebMethod()>
Private Shared Function Test() As String
Dim msg As String = "Horray"
Return msg
End Function
End Class
the success function of the ajax-call is being executed...

Related

In a Shared (VB) webmethod the Request.Files is not accessible

from javascript an ajax call to the server is done.
javascript:
function SaveNote() {
var note = quill.root.innerHTML;
var postData = { mediaNote: note };
console.log("SaveNote is called");
$.ajax({
type: "POST",
data: JSON.stringify(postData),
url: "EditTextReport.aspx/SaveNote",
contentType: "application/json; charset=utf-8",
dataType: "json",
traditional: true,
success: function (data) {
console.log("SaveNote returned from server with success");
return;
},
error: function (error) {
console.log(error);
}
});
}
Visual Basic code:
Public Shared Sub SaveNote(mediaNote As String)
_noteContent = mediaNote
_IsNoteReceived = True
_staticMe.Save(False)
End Sub
Public Sub Save(sendEmailAfterSave As Boolean)
...
Dim flImages As HttpFileCollection = Request.Files
...
End Sub
On the serverside the request object is needed but this throws an exception:
System.Web.HttpException: 'Request is not available in this context'
I'm looking to find a way of getting the Request object send with the ajax call to the server as a parameter, so it can be used in a shared(static) context.

PareserError Function was not called

I am getting this error and I do not know how to get passed it. I am trying to do an ajax call to populate my data store. The error is:
Parsererror 'function' was not called when I do this :
var customStore = new DevExpress.data.CustomStore({
load: function () {
return $.ajax({
url: 'URL/Service/GetCustomers?callback=?fnsuccesscallback',
crossOrigin: true,
crossDomain: true,
jsonp: true,
type: 'GET',
dataType: 'jsonp',
contentType: "application/json; charset=utf-8",
jsonpCallback: 'fnsuccesscallback',
async: false,
success: function (res) {
console.log("success");
res = JSON.parse(res);
console.log("data _" + res);
},
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
}
});
var fnsuccesscallback = function (data) {
alert(data);
};
var gridDataSourceConfiguration = {
store: customStore
};
My Service code for this function is :
Function GetCustomers() As Stream Implements IService.GetCustomers
Try
Dim Cust As List(Of Customers) = New List(Of Customers)
Dim SQLSTR As String = ""
SQLSTR = "Select Code, Name, ID FROM Table"
Dim ErrorMessage As String = ""
ErrorMessage = Obj.OpenConnection(SQLServer, UmbrellaDatabase, UserCode, UserPassword)
If ErrorMessage <> "" Then
System.Diagnostics.EventLog.WriteEntry("APP", ErrorMessage, EventLogEntryType.Error)
WebOperationContext.Current.OutgoingResponse.StatusCode = 501
WebOperationContext.Current.OutgoingResponse.StatusDescription = ErrorMessage
Return Nothing
Else
Dim CustomerDetails As DataSet
CustomerDetails = tObj.GetDataSQL(SQLSTR)
If Not CustomerDetails Is Nothing Then
CustomerDetails.DataSetName = "Companies"
CustomerDetails.Tables(0).TableName = "Companies"
Dim CustomerTable As DataTable
Dim CustomerRow As DataRow
If CustomerDetails.Tables.Count > 0 Then
CustomerTable = CustomerDetails.Tables(0)
If CustomerTable.Rows.Count > 0 Then
Dim i As Integer
For i = 0 To CustomerTable.Rows.Count - 1
CustomerRow = CustomerTable.Rows(i)
Dim CC As New Customers
CC.Code = CustomerRow.Item("Code")
CC.Name = CustomerRow.Item("Name")
CC.InternalID = CustomerRow.Item("InternalID")
Cust.Add(CC)
Next i
' Serialize the results as JSON
Dim serializer As DataContractJsonSerializer = New DataContractJsonSerializer(Cust.GetType())
Dim Stream As MemoryStream = New MemoryStream
serializer.WriteObject(Stream, Cust)
' Return the results serialized as JSON
Dim json As String = Encoding.Default.GetString(Stream.ToArray())
Return New MemoryStream(Encoding.UTF8.GetBytes(json))
Obj.CloseConnection()
WebOperationContext.Current.OutgoingResponse.StatusCode = 200
WebOperationContext.Current.OutgoingResponse.StatusDescription = "OK"
End If
End If
Else
System.Diagnostics.EventLog.WriteEntry("APP", ErrorMessage, EventLogEntryType.Error)
WebOperationContext.Current.OutgoingResponse.StatusCode = 501
WebOperationContext.Current.OutgoingResponse.StatusDescription = ErrorMessage
Cust = Nothing
Return Nothing
End If
End If
Catch ex As Exception
System.Diagnostics.EventLog.WriteEntry("Umbrella Mobile Service", ex.Message, EventLogEntryType.Error)
WebOperationContext.Current.OutgoingResponse.StatusCode = 501
WebOperationContext.Current.OutgoingResponse.StatusDescription = ex.Message
Return Nothing
End Try
Dispose()
End Function
How should my JSON output look like in my service in order to send out the correct callback? What should I do in order for this error not to show?

MVC - Redirect after authentication and remember

I have a MVC Login page where I authenticate the user with an AJAX post method.
I want to redirect the user from Home/Index to another controller method Home/Main once the username and password are authenticated.
Here's my home controller:
Function Index() As ActionResult
Return View()
End Function
Function Main() As ActionResult
Return View()
End Function
Here is my ajax post method:
<script type="text/javascript">
$(document).ready(function () {
$('#BtnLogin').click(function () {
var userInfo = {
UserName: $('#txtusername').val(),
Password: $('#TxtPassword').val()
};
$.ajax({
url: '#Url.Content("~/api/Users/CheckUser")',
type: 'POST',
data: JSON.stringify(userInfo),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (responseData) {
for (var i = 0; i < responseData.length; i++) {
if (responseData[i].isErrorBool == '1') {
document.getElementById("LblErrors").innerHTML = responseData[i].isErrorMessage;
}
else {
//redirect
}
}
}
});
});
});
</script>
And my Web API:
<HttpPost>
Public Function CheckUser(LGIN As LoginModel) As List(Of VerifyReturnLogin)
Dim ReturnJson = Nothing
Dim sb As New StringBuilder()
Dim sw As New StringWriter(sb)
Try
Using jsonWriter As JsonWriter = New JsonTextWriter(sw)
jsonWriter.WriteStartArray()
jsonWriter.WriteStartObject()
Dim c As List(Of UserProfile) = userRepository.CheckUser(LGIN.UserName.Trim, LGIN.Password.Trim)
If c.Count = 0 Or c Is Nothing Then
jsonWriter.WritePropertyName("isErrorBool")
jsonWriter.WriteValue("1")
jsonWriter.WritePropertyName("isErrorMessage")
jsonWriter.WriteValue("Wrong Username or Password.")
jsonWriter.WriteEndObject()
jsonWriter.WriteEndArray()
ReturnJson = JsonConvert.DeserializeObject(Of List(Of VerifyReturnLogin))(sb.ToString)
Return ReturnJson
Else
'Redirect to Home/Main
End If
End Using
Catch ex As Exception
End Try
End Function
Where is the best place to redirect? Client or Server side?
And After login, is it wise to use Sessions in MVC like they are used in ASP.net, to ensure that the user is authenticated to go to Home/Main on every refresh?
Any help would be appreciated.
You should use in javascript window.location = "http://www.yoururl.com"; when you have
//redirect

Returning a List of entity objects from ajax

I am new to ajax and I am trying to return a list of entity objects via ajax. When I do this with string it works successfully.
my ajax code:
$.ajax({
type: "POST",
url: "/MemberPages/AdminPages/AddProduct.aspx/GetList",
data: '{"categoryId":' + $('#<%=ddlCategory.ClientID %> option:selected').val() + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var cats = msg.d;
$.each(cats, function (index, cat) {
alert(cat);
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
my code that returns a string:
[WebMethod]
public static List<String> GetList(int categoryId)
{
List<String> catlist = new List<String>();
IQueryable<SubCategory> clist = new ProductsBL().GetSubCategories(categoryId);
foreach (SubCategory c in clist)
{
catlist.Add(c.Name.ToString());
}
return catlist;
}
my code that gives a 500 internal server error
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<SubCategory> GetList(int categoryId)
{
List<SubCategory> catlist = new List<SubCategory>();
IQueryable<SubCategory> clist = new ProductsBL().GetSubCategories(categoryId);
foreach (SubCategory c in clist)
{
catlist.Add(c);
}
return catlist;
}
Thanks For any help as I have spent a considerable amount of time trying to wrap my head around it.
I think you have to remove the external quotes to the "data" in the jQuery call
data: {categoryId: $('#<%=ddlCategory.ClientID %> option:selected').val() },
Otherwise you submit a String, not the intended request composed by parameter called categoryId and valued as extracted from the selected option

ajax call always going to the same method in my web api

EDIT: PER Felipe's answer, I changed the code in the webapiconfig to the following, and it works great-
config.Routes.MapHttpRoute( _
name:="DefaultApi", _
routeTemplate:="api/{controller}/{action}/{id}", _
defaults:=New With {.id = RouteParameter.Optional} _
)
config.Routes.MapHttpRoute(name:="API Default", routeTemplate:="api/{controller}/{action}/{id}", defaults:=New With { _
.id = RouteParameter.[Optional] _
})
I have a web api controller with 4 functions-
<HttpGet> _
<ActionName("AllCerts")> _
Public Function GetCerts() As Object
Dim LWCERTS As Array = objCert.GetCertificates
Return LWCERTS
End Function
<HttpGet> _
<ActionName("MyCerts")> _
Public Function GetMyCert() As Object
Dim lwMyCerts As Array = objCert.GetCertificates(Utilities.GetLogin())
Return lwMyCerts
End Function
<HttpGet> _
<ActionName("GetValueDDA")> _
Public Function GetDDABanks()
Dim objDDABankNum As New LucasEntities.Business.EF_DDA
Dim lwDDABankNum As Array = objDDABankNum.GetDDABankJSON()
Return lwDDABankNum
End Function
'' POST api/caapproval
<HttpPost> _
<ActionName("CertDtlsByID")> _
Public Function Post(value As CertDetailModel) As Object
Dim objCertPosting As New LucasEntities.Business.EF_CertificatePosting
Dim lwMyCertDetails As String = objCertPosting.GetBorrowingBaseAdvanceRequestJSON()
Return lwMyCertDetails
End Function
In my data service, I have the following ajax call-
var getallCertificates = function (CertificatesObservable) {
var dataObservableArray = ko.observableArray([]);
var newJ;
$.ajax({
type: "GET",
dataType: "json",
url: "/api/caapproval/AllCerts/",
async: false,
success: function (dataIn) {
newJ = $.parseJSON(dataIn);
CertificatesObservable([]);
dataIn.forEach(function (p) {
var certificate = new certificateModel(p.clientID, p.lwCertID, p.requestDate, p.userName, p.statusDescription, p.statusCode, p.statusDesc, p.ceoUserName, p.clientName, p.clientNumber, p.borrowBaseCount, p.advRequestCount, p.certType);
CertificatesObservable.push(certificate);
});
return CertificatesObservable(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
//jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 });
}
});
return CertificatesObservable(newJ);
}
Here is my RouteConfig class-
Public Class RouteConfig
Public Shared Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
routes.MapRoute( _
name:="Default", _
url:="{controller}/{action}/{id}", _
defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional} _
)
End Sub
End Class
When I put breakpoints in my controller, I see that the Post function under the CertDtlsByID actionName is always run, NOT GetCerts under the AllCerts ActionName. Being new to web api and routing, what am i doing wrong that causes the "Post" method to always be called?
When I run the web api directly in the browser, Chrome shows the following error-
Multiple actions were found that match the request: System.Object GetCerts() on type LucasNetApp.CAApprovalController System.Object GetMyCert() on type LucasNetApp.CAApprovalController System.Object GetDDABanks() on type LucasNetApp.CAApprovalController
In asp.net web api the routing is controlled by the WebApiConfig.cs file on the App_Start folder.
The ActionName attribute does not work because it is a behavouir of the asp.net mvc.
Open the WebApiConfig.cs file and try to add theses routes configurations:
config.Routes.MapHttpRoute(name:="DefaultApiGet",
url:="api/{controller}",
defaults:=New With {.action = "Get"},
constraints:=new With {.httpMethod = new HttpMethodConstraint(HttpMethod.Get)})
config.Routes.MapHttpRoute(name:="DefaultApiWithAction",
url:="api/{controller}/{action}")
I am not sure about the Vb.Net sintaxe, looks the same code in C#:
config.Routes.MapHttpRoute("DefaultApiGet",
"api/{controller}",
new {action = "Get"},
new {httpMethod = new HttpMethodConstraint(HttpMethod.Get)});
config.Routes.MapHttpRoute("DefaultApiWithAction",
"api/{controller}/{action}");

Resources