HttpClient consume Odata Not Working - xamarin.forms

I use below code to access SAP Odata WebService:
string strUrl = "https://...../HandlingUnitSet?$format=json";
var credentials = new NetworkCredential("user", "usr123");
var handler = new HttpClientHandler { Credentials = credentials };
var client = new System.Net.Http.HttpClient(handler);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json");
var response = await client.GetAsync(strUrl);
string status = response.StatusCode.ToString();
string header = response.Headers.ToString();
string cont = response.Content.ToString();
string contactsJson = response.Content.ReadAsStringAsync().Result;
UoUnit ObjUnitList = new UoUnit();
ObjUnitList = JsonConvert.DeserializeObject<UoUnit>(contactsJson);
The Problem : I got the below error message
The url suppose to return Json Data but I did not get it. This error encountered at the line of DeserializeObject
Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
at Newtonsoft.Json.JsonTextReader.ParseValue ()
{Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.
at Newtonsoft.Json.JsonTextReader.ParseValue () [0x002b3] in <d32db49e5e3440729da31845c03ddc3a>:0
at Newtonsoft.Json.JsonTextReader.Read () [0x0004c] in <d32db49e5e3440729da31845c03ddc3a>:0
at Newtonsoft.Json.JsonReader.ReadAndMoveToContent () [0x00000] in <d32db49e5e3440729da31845c03ddc3a>:0
at Newtonsoft.Json.JsonReader.ReadForType (Newtonsoft.Json.Serialization.JsonContract contract, System.Boolean hasConverter) [0x0004a] in <d32db49e5e3440729da31845c03ddc3a>:0
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType, System.Boolean checkAdditionalContent) [0x000db] in <d32db49e5e3440729da31845c03ddc3a>:0
at Newtonsoft.Json.JsonSerializer.DeserializeInternal (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00054] in <d32db49e5e3440729da31845c03ddc3a>:0
at Newtonsoft.Json.JsonSerializer.Deserialize (Newtonsoft.Json.JsonReader reader, System.Type objectType) [0x00000] in <d32db49e5e3440729da31845c03ddc3a>:0
at Newtonsoft.Json.JsonConvert.DeserializeObject (System.String value, System.Type type, Newtonsoft.Json.JsonSerializerSettings settings) [0x0002d] in <d32db49e5e3440729da31845c03ddc3a>:0
at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value, Newtonsoft.Json.JsonSerializerSettings settings) [0x00000] in <d32db49e5e3440729da31845c03ddc3a>:0
at Newtonsoft.Json.JsonConvert.DeserializeObject[T] (System.String value) [0x00000] in <d32db49e5e3440729da31845c03ddc3a>:0
}

Related

Xamarin Forms: Issue with file upload (Xamarin.Essentials)

I was using Plugin.FilePicker to pick files from the device. It was working fine on android version 11 and below. But on android version 12 and above, it is breaking with below exception:
Java.Lang.NullPointerException: uri
at Java.Interop.JniEnvironment+InstanceMethods.CallNonvirtualObjectMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniObjectReference type, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00088] in /Users/runner/work/1/s/xamarin-android/external/Java.Interop/src/Java.Interop/obj/Release/JniEnvironment.g.cs:11928
at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeNonvirtualObjectMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0001e] in /Users/runner/work/1/s/xamarin-android/external/Java.Interop/src/Java.Interop/Java.Interop/JniPeerMembers.JniInstanceMethods_Invoke.cs:894
at Android.Content.ContentResolver.Query (Android.Net.Uri uri, System.String[] projection, System.String selection, System.String[] selectionArgs, System.String sortOrder) [0x000a0] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/obj/Release/monoandroid10/android-33/mcw/Android.Content.ContentResolver.cs:1456
at Plugin.FilePicker.IOUtil.GetDataColumn (Android.Content.Context context, Android.Net.Uri uri, System.String selection, System.String[] selectionArgs) [0x00013] in D:\a\1\s\src\Plugin.FilePicker\Android\IOUtil.android.cs:151
at Plugin.FilePicker.IOUtil.GetPath (Android.Content.Context context, Android.Net.Uri uri) [0x00167] in D:\a\1\s\src\Plugin.FilePicker\Android\IOUtil.android.cs:108
at Plugin.FilePicker.FilePickerActivity.OnActivityResult (System.Int32 requestCode, Android.App.Result resultCode, Android.Content.Intent data) [0x00039] in D:\a\1\s\src\Plugin.FilePicker\Android\FilePickerActivity.android.cs:151
--- End of stack trace from previous location where exception was thrown ---
at Plugin.FilePicker.FilePickerImplementation.PickFile (System.String[] allowedTypes) [0x00028] in D:\a\1\s\src\Plugin.FilePicker\Android\FilePickerImplementation.android.cs:60
at CatholicBrain.ConnectAppModule.CreateActivityPage.PickFile (System.Object sender, System.EventArgs args) [0x00075] in :0
--- End of managed Java.Lang.NullPointerException stack trace ---
java.lang.NullPointerException: uri
at java.util.Objects.requireNonNull(Objects.java:245)
at android.content.ContentResolver.query(ContentResolver.java:1225)
at android.content.ContentResolver.query(ContentResolver.java:1184)
at android.content.ContentResolver.query(ContentResolver.java:1140)
at crc64424a8adc5a1fbe28.FilePickerActivity.n_onActivityResult(Native Method)
at crc64424a8adc5a1fbe28.FilePickerActivity.onActivityResult(FilePickerActivity.java:48)
at android.app.Activity.dispatchActivityResult(Activity.java:8840)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5694)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5740)
at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:54)
at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2458)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loopOnce(Looper.java:233)
at android.os.Looper.loop(Looper.java:334)
at android.app.ActivityThread.main(ActivityThread.java:8501)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:582)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
I checked for any updates for Plugin.FilePicker and found that the package is deprecated. So I installed the Xamarin.Essentials package and updated codes for picking files. It is working fine on android version 12 and above.
Xamarin.Essentials.FileResult file = null;
file = await FilePicker.PickAsync();
if (file != null)
{
filename_label.IsVisible = true;
filename_label.Text = file.FileName;
upload_layout.IsVisible = true;
}
But when I try to upload the file using our REST API it fails with below exception:
System.IO.FileNotFoundException: hail-mary.pdf
File name: 'hail-mary.pdf' ---> Java.IO.FileNotFoundException: hail-mary.pdf
at Java.Interop.JniEnvironment+InstanceMethods.CallObjectMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00068] in /Users/runner/work/1/s/xamarin-android/external/Java.Interop/src/Java.Interop/obj/Release/JniEnvironment.g.cs:11524
at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeAbstractObjectMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0001e] in /Users/runner/work/1/s/xamarin-android/external/Java.Interop/src/Java.Interop/Java.Interop/JniPeerMembers.JniInstanceMethods_Invoke.cs:848
at Android.Content.Res.AssetManager.Open (System.String fileName) [0x0001f] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/obj/Release/monoandroid10/android-33/mcw/Android.Content.Res.AssetManager.cs:265
at Xamarin.Essentials.FileSystem.PlatformOpenAppPackageFileAsync (System.String filename) [0x0001d] in D:\a_work\1\s\Xamarin.Essentials\FileSystem\FileSystem.android.cs:48
--- End of managed Java.IO.FileNotFoundException stack trace ---
java.io.FileNotFoundException: hail-mary.pdf
at android.content.res.AssetManager.nativeOpenAsset(Native Method)
at android.content.res.AssetManager.open(AssetManager.java:893)
at android.content.res.AssetManager.open(AssetManager.java:870)
at crc64ee486da937c010f4.ButtonRenderer.n_onClick(Native Method)
at crc64ee486da937c010f4.ButtonRenderer.onClick(ButtonRenderer.java:107)
at android.view.View.performClick(View.java:7512)
at android.view.View.performClickInternal(View.java:7489)
at android.view.View.access$3700(View.java:857)
at android.view.View$PerformClick.run(View.java:29034)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:233)
at android.os.Looper.loop(Looper.java:334)
at android.app.ActivityThread.main(ActivityThread.java:8501)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:582)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1068)
at Xamarin.Essentials.FileSystem.PlatformOpenAppPackageFileAsync (System.String filename) [0x00036] in D:\a_work\1\s\Xamarin.Essentials\FileSystem\FileSystem.android.cs:52
at Xamarin.Essentials.FileSystem.OpenAppPackageFileAsync (System.String filename) [0x00000] in D:\a_work\1\s\Xamarin.Essentials\FileSystem\FileSystem.shared.cs:16
at CatholicBrain.ConnectAppModule.CreateActivityPage.UploadFile (System.Object sender, System.EventArgs e) [0x00126] in <8fb254ba200e4d369cb3f96cc3e665ff>:0
Upload Code:
var content = new MultipartFormDataContent();
Stream stream = await FileSystem.OpenAppPackageFileAsync(file.FileName);
byte[] data;
using (MemoryStream ms = new MemoryStream())
{
stream.CopyTo(ms);
data = ms.ToArray();
ms.Dispose();
}
content.Add(new StreamContent(stream), "\"fileUpload\"", $"\"{file.FullPath}\"");
var httpClient = new HttpClient();
var response = await httpClient.PostAsync(new Uri(REST API Path), content);
file.FullPath is provided on the upload code but getting FileNotFoundException.
If you use FilePicker.PickAsync(); to get the file, you do not need to use Stream stream = await FileSystem.OpenAppPackageFileAsync(file.FullPath); to read it to stream.
Just use Stream stream = await file.OpenReadAsync(); directly, then you can get the stream.

JavaScriptCanOpenWindowsAutomatically make my android Xamarin forms app crashes

I'm using a custom renderer on a WebView in my project, and I need it to be able to open popups, then I added JavaScriptCanOpenWindowsAutomatically settings to the constructor, but if I set it to true the app crashes at launch, here is my renderer:
[assembly: ExportRenderer(typeof(Xamarin.Forms.WebView), typeof(HybridWebViewRenderer))]
namespace ClotureSiadForms.Droid.Renderer
{
internal class HybridWebViewRenderer : WebViewRenderer
{
public HybridWebViewRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.Settings.JavaScriptEnabled = true;
Control.Settings.DomStorageEnabled = true;
Control.Settings.SavePassword = true;
//Control.Settings.JavaScriptCanOpenWindowsAutomatically = true;
}
}
}
}
And the error:
10-19 19:05:55.667 HUAWEI RNE-L21 Error 24197 mono-rt [ERROR] FATAL UNHANDLED EXCEPTION: System.TypeInitializationException: The type initializer for 'Types' threw an exception. ---> System.EntryPointNotFoundException: java_interop_jvm_list assembly:<unknown assembly> type:<unknown type> member:(null)
at (wrapper managed-to-native) Java.Interop.NativeMethods.java_interop_jvm_list(intptr[],int,int&)
at Java.Interop.JniRuntime.GetCreatedJavaVMs (System.IntPtr[] handles, System.Int32 bufLen, System.Int32& nVMs) [0x00000] in <d12ba608ed5a4079a11cd8a7188dddcf>:0
at Java.Interop.JniRuntime.GetAvailableInvocationPointers () [0x00000] in <d12ba608ed5a4079a11cd8a7188dddcf>:0
at Java.Interop.JniRuntime.get_CurrentRuntime () [0x00095] in <d12ba608ed5a4079a11cd8a7188dddcf>:0
at Java.Interop.JniEnvironmentInfo..ctor () [0x00006] in <d12ba608ed5a4079a11cd8a7188dddcf>:0
at Java.Interop.JniEnvironment+<>c.<.cctor>b__35_0 () [0x00000] in <d12ba608ed5a4079a11cd8a7188dddcf>:0
at System.Threading.ThreadLocal`1[T].GetValueSlow () [0x00031] in <a790ddc2dda1484d9a4b87dd85c6ca47>:0
at System.Threading.ThreadLocal`1[T].get_Value () [0x0003e] in <a790ddc2dda1484d9a4b87dd85c6ca47>:0
at Java.Interop.JniEnvironment+Types.TryFindClass (System.String classname, System.Boolean throwOnError) [0x00014] in <d12ba608ed5a4079a11cd8a7188dddcf>:0
at Java.Interop.JniEnvironment+Types.FindClass (System.String classname) [0x00000] in <d12ba608ed5a4079a11cd8a7188dddcf>:0
at Java.Interop.JniType..ctor (System.String classname) [0x00006] in <d12ba608ed5a4079a11cd8a7188dddcf>:0
at Java.Interop.JniEnvironment+Types..cctor () [0x000d2] in <d12ba608ed5a4079a11cd8a7188dddcf>:0
--- End of inner exception stack trace ---
at Android.Runtime.JNIEnv.IsInstanceOf (System.IntPtr obj, System.IntPtr clazz) [0x0000e] in <ac4226d0aad24df781f4097e7b8b972f>:0
at Android.Runtime.JNIEnv.IsGCUserPeer (System.IntPtr value) [0x0000f] in <ac4226d0aad24df781f4097e7b8b972f>:0
Then, is there another way to make blank links open in the default browser ? Or to prevent this error ?

Getting exception when adding pin to Mapsui (Xamarin Forms)

I am trying to add a pin to my Xamarin Forms Mapsui control.
Here is my Xaml
<mapsui:MapView x:Name="selectMapControl"
VerticalOptions="FillAndExpand"
HorizontalOptions="Fill"
BackgroundColor="Gray" />
Here is my code:
protected override void OnAppearing()
{
base.OnAppearing();
var map = new Map
{
CRS = "EPSG:3857",
Transformation = new MinimalTransformation()
};
var tileLayer = OpenStreetMap.CreateTileLayer();
map.Layers.Add(tileLayer);
map.Widgets.Add(new Mapsui.Widgets.ScaleBar.ScaleBarWidget(map) { TextAlignment = Mapsui.Widgets.Alignment.Center, HorizontalAlignment = Mapsui.Widgets.HorizontalAlignment.Left, VerticalAlignment = Mapsui.Widgets.VerticalAlignment.Bottom });
selectMapControl.Map = map;
double lat = 36.9628066;
double lng = -122.0194722;
var myPosition = new Position(lat, lng);
var myPin = new Pin(selectMapControl) //Exception here
{
Position = myPosition,
Type = PinType.Pin,
Label = "Zero point",
Address = "Zero point",
};
selectMapControl.Pins.Add(myPin);
}
I receive an "Object reference not set to an instance of an object.'" exception on the line var myPin = new Pin(selectMapControl)...
If my lat and lng are both set to 0 then it works
Here is the stack trace in the exception:
at Mapsui.UI.Forms.Pin.OnPropertyChanged (System.String propertyName) [0x001df] in <5cc65edf513349cdba641e049bbf0143>:0
at Xamarin.Forms.BindableObject.SetValueActual (Xamarin.Forms.BindableProperty property, Xamarin.Forms.BindableObject+BindablePropertyContext context, System.Object value, System.Boolean currentlyApplying, Xamarin.Forms.Internals.SetValueFlags attributes, System.Boolean silent) [0x00114] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:510
at Xamarin.Forms.BindableObject.SetValueCore (Xamarin.Forms.BindableProperty property, System.Object value, Xamarin.Forms.Internals.SetValueFlags attributes, Xamarin.Forms.BindableObject+SetValuePrivateFlags privateAttributes) [0x00173] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:446
at Xamarin.Forms.BindableObject.SetValue (Xamarin.Forms.BindableProperty property, System.Object value, System.Boolean fromStyle, System.Boolean checkAccess) [0x0004d] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:374
at Xamarin.Forms.BindableObject.SetValue (Xamarin.Forms.BindableProperty property, System.Object value) [0x00000] in D:\a\1\s\Xamarin.Forms.Core\BindableObject.cs:349
at Mapsui.UI.Forms.Pin.set_Position (Mapsui.UI.Forms.Position value) [0x00000] in <5cc65edf513349cdba641e049bbf0143>:0
at eLunaApp.Views.RestaurantMapPage.OnAppearing () [0x0008d] in C:\x\elunaapp\eLunaApp\PageRestaurantMap\RestaurantMapPage.xaml.cs:82
at Xamarin.Forms.Page.SendAppearing () [0x00045] in D:\a\1\s\Xamarin.Forms.Core\Page.cs:452
at Xamarin.Forms.ShellContent.SendPageAppearing (Xamarin.Forms.Page page) [0x0003b] in D:\a\1\s\Xamarin.Forms.Core\Shell\ShellContent.cs:127
at Xamarin.Forms.ShellContent.SendAppearing () [0x00019] in D:\a\1\s\Xamarin.Forms.Core\Shell\ShellContent.cs:108
at Xamarin.Forms.ShellContent.OnChildAdded (Xamarin.Forms.Element child) [0x00021] in D:\a\1\s\Xamarin.Forms.Core\Shell\ShellContent.cs:138
at Xamarin.Forms.ShellContent.set_ContentCache (Xamarin.Forms.Page value) [0x0003b] in D:\a\1\s\Xamarin.Forms.Core\Shell\ShellContent.cs:182
at Xamarin.Forms.ShellContent.Xamarin.Forms.IShellContentController.GetOrCreateContent () [0x0003c] in D:\a\1\s\Xamarin.Forms.Core\Shell\ShellContent.cs:68
at Xamarin.Forms.Platform.Android.ShellSectionRenderer.OnCreateView (Android.Views.LayoutInflater inflater, Android.Views.ViewGroup container, Android.OS.Bundle savedInstanceState) [0x000f2] in D:\a\1\s\Xamarin.Forms.Platform.Android\Renderers\ShellSectionRenderer.cs:166
at AndroidX.Fragment.App.Fragment.n_OnCreateView_Landroid_view_LayoutInflater_Landroid_view_ViewGroup_Landroid_os_Bundle_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_inflater, System.IntPtr native_container, System.IntPtr native_savedInstanceState) [0x00021] in D:\a\1\s\generated\androidx.fragment.fragment\obj\Release\monoandroid90\generated\src\AndroidX.Fragment.App.Fragment.cs:1950
at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.50(intptr,intptr,intptr,intptr,intptr)

ASP.NET redirect error

I have controller "HomeController" class with two actions ("Index" and "Login"). By condition I must redirect user from "Index" to "Login". I tried next code:
if(HomeController.LoggedIn()) {
return View();
}
else {
return RedirectToAction("Login", "Home", new { area = "" });
}
But it throws error :
Description: HTTP 500.Error processing request.
Details: Non-web exception. Exception origin (name of application or object): System.Web.Mvc.
Exception stack trace:
at System.Web.Mvc.RouteCollectionExtensions.GetVirtualPathForArea (System.Web.Routing.RouteCollection routes, System.Web.Routing.RequestContext requestContext, System.String name, System.Web.Routing.RouteValueDictionary values, System.Boolean& usingAreas) [0x00000] in <filename unknown>:0
at System.Web.Mvc.RouteCollectionExtensions.GetVirtualPathForArea (System.Web.Routing.RouteCollection routes, System.Web.Routing.RequestContext requestContext, System.String name, System.Web.Routing.RouteValueDictionary values) [0x00000] in <filename unknown>:0
at System.Web.Mvc.UrlHelper.GenerateUrl (System.String routeName, System.String actionName, System.String controllerName, System.Web.Routing.RouteValueDictionary routeValues, System.Web.Routing.RouteCollection routeCollection, System.Web.Routing.RequestContext requestContext, Boolean includeImplicitMvcValues) [0x00000] in <filename unknown>:0
at System.Web.Mvc.RedirectToRouteResult.ExecuteResult (System.Web.Mvc.ControllerContext context) [0x00000] in <filename unknown>:0
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult (System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ActionResult actionResult) [0x00000] in <filename unknown>:0
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive (IList`1 filters, Int32 filterIndex, System.Web.Mvc.ResultExecutingContext preContext, System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ActionResult actionResult) [0x00000] in <filename unknown>:0
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive (IList`1 filters, Int32 filterIndex, System.Web.Mvc.ResultExecutingContext preContext, System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ActionResult actionResult) [0x00000] in <filename unknown>:0
What I'm doing wrong?
Please, make sure about even route config as per requirement is there or not ?
Or
try to pass a value in thirs parameter as id or value like:
if(HomeController.LoggedIn()) {
return View();
}
else {
return RedirectToAction("Login", "Home", "");
}
To specify the default area, just use:
return RedirectToAction("Login", "Home");

How to pass arrays to webservice in asp.net

I am trying to pass an array as a parameter in ajax but i am receiving an error. Kindly please tell me how to pass arrays to a web service.
Error
{"Message":"Type \u0027System.String\u0027 is not supported for deserialization of an array.","StackTrace":" at System.Web.Script.Serialization.ObjectConverter.ConvertListToObject(IList list, Type type, JavaScriptSerializer serializer, Boolean throwOnError, IList\u0026 convertedList)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.AddItemToList(IList oldList, IList newList, Type elementType, JavaScriptSerializer serializer, Boolean throwOnError)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertListToObject(IList list, Type type, JavaScriptSerializer serializer, Boolean throwOnError, IList\u0026 convertedList)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\r\n at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\r\n at System.Web.Script.Services.WebServiceMethodData.StrongTypeParameters(IDictionary`2 rawParams)\r\n at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
Webservice method
[WebMethod(Description = "Add Session List")]
[ScriptMethod(UseHttpGet = false)]
public stringAddSession(string org, string ins, string brn, string startdate, string enddate, string[] classes, string[] subjects, object[] classsubjects)
{
return "abc";
}
ajax call
$.ajax({
type: "POST",
url: /Services/session/SessionService.asmx/AddSession,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'org': OrgID, 'ins': InsID, 'brn': BrnID, 'startdate': StartDate, 'enddate': EndDate, 'classes': Classes, 'subjects': Subjects, 'classsubjects': ClassesWithSubjects };),
dataType: "json",
processData: false,
success: object,
error: function (err) {
console.log("AJAX ERROR");
alert(err.responseText);
}
});
Here is the request Payload
You can achieve also achieve same thing by using below code snippet.
var classes = new Array();
classes.push('calss1');
classes.push('class2');
var data = new Object();
data.org = OrgID; //How to add object
data.classes = classes; //How to add array
.......
.......
data: JSON.stringify(data);
.......
.......

Resources