How to pass arrays to webservice in asp.net - 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);
.......
.......

Related

No parameterless constructor defined for type

I am trying to learn and to do something with asp.net. I'm trying to get some info from json api using import.io's api, but i could not figure out something. I am trying to solve it till 2 days:
ERROR : No parameterless constructor defined for type of 'imdb_io_web.IMDB[]'
Why am I getting that error I really don't understand?
I have a class
namespace imdb_io_web
{
public class IMDB
{
public string director { get; set; }
}
}
and trying to get director name from IMDB
var wc = new WebClient();
var serializer = new JavaScriptSerializer();
var result = serializer.Deserialize<IMDB[]>(wc.DownloadString("MYAPI"));
foreach (var item in result) { Label1.Text = item.director; }
[MissingMethodException: No parameterless constructor defined for type of 'imdb_io_web.IMDB[]'.]
System.Web.Script.Serialization.ObjectConverter.ConvertDictionaryToObject(IDictionary`2 dictionary, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject) +527729
System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject) +66
System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object& convertedObject) +145
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) +66
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(String input) +70
imdb_io_web.WebForm1.Page_Load(Object sender, EventArgs e) in C:\Users\ahmetozsari\documents\visual studio 2010\Projects\imdb_io_web\imdb_io_web\WebForm1.aspx.cs:26
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
Either you deserialize a single element:
var result = serializer.Deserialize<IMDB>(wc.DownloadString("MYAPI"));
Label1.Text = item.director;
or a list
var result = serializer.Deserialize<List<IMDB>>(wc.DownloadString("MYAPI"));
foreach (var item in result) { Label1.Text = item.director; }
The array type (IMDB[]), as you read in the exception, cannot be used as a type parameter for the deserializer as it lacks the parameterless constructor. Using List<IMDB> should possibly resolve the issue.
Firstly you can use HttpClient class for API operations.
using (var httpClient = new HttpClient())
{
var operationResult = await httpClient.GetStringAsync(#"http://localhost/api/requests");
}
Secondly, for JSON conversion operations you can use Json.NET
using Newtonsoft.Json;
public class RequestJson
{
[JsonProperty("request")]
public Request Request { get; set; }
}
public class Request
{
[JsonProperty("name")]
public string Name{ get; set; }
}
JsonConvert.DeserializeObject<List<RequestJson>>(operationResult );
You have to use List template type because with my understanding when you are creating an array type then Newtonsoft.Json would not be able to instantiate the object because it needs a size.

Controller Action ambiguity even with [HttpPost] attribute? (ASP.NET MVC4)

So I have a "Register" view (that maps to a RegisterController), which is a simple form for people to register in my service. Given that the form's method is POST, then I can name both actions of the controller (the one that shows the form, and the one that receives its submission) the same name, but discriminate them via the [HttpPost] attribute, this way:
open System
open System.Web
open System.Web.Mvc
open System.Net
open System.Threading
open System.Configuration
[<HandleError>]
type RegisterController() =
inherit Controller()
member this.Index (guid: string) =
let model = new RegisterModel(guid)
this.View("Register", model) :> ActionResult
[<HttpPost>]
member this.Index
(guid: string, password: string, passwordRetry: string) =
if not (password.Equals(passwordRetry)) then
raise(new Exception("Passwords must be the same"))
WebDbAccess.SetNewPassword guid password
RedirectResult("/") :> ActionResult
This works perfectly.
However, I just tried to use this same technique in the Home view of my app (for the Login functionality), and it doesn't work! It throws this:
The current request for action 'Index' on controller type 'HomeController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Index(System.String, System.String) on type FsWeb.Controllers.HomeController
System.Web.Mvc.ActionResult Index() on type FsWeb.Controllers.HomeController
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Reflection.AmbiguousMatchException: The current request for action 'Index' on controller type 'HomeController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Index(System.String, System.String) on type FsWeb.Controllers.HomeController
System.Web.Mvc.ActionResult Index() on type FsWeb.Controllers.HomeController
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[AmbiguousMatchException: The current request for action 'Index' on controller type 'HomeController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Index(System.String, System.String) on type FsWeb.Controllers.HomeController
System.Web.Mvc.ActionResult Index() on type FsWeb.Controllers.HomeController]
System.Web.Mvc.Async.AsyncActionMethodSelector.FindAction(ControllerContext controllerContext, String actionName) +495852
System.Web.Mvc.Async.ReflectedAsyncControllerDescriptor.FindAction(ControllerContext controllerContext, String actionName) +57
System.Web.Mvc.ControllerActionInvoker.FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, String actionName) +16
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +114
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929
What's the difference between the 2 cases? I don't get it.
The HomeController's implementation is:
open System
open System.Web
open System.Web.Http
[<HandleError>]
type HomeController() =
inherit Controller()
[<HttpGet>]
member this.Index () =
this.View() :> ActionResult
[<HttpPost>]
member this.Index
(id:string, password:string) =
if (UserIsValid id password) then
RedirectResult("lobby") :> ActionResult
RedirectResult("loginError") :> ActionResult
#nemesv was right, I had to fully qualify HttpPost with System.Web.Mvc.HttpPost because otherwise it would use System.Web.Http.HttpPost!!

Simple.Data Insert Object - List initializers must contain at least one initializer

When I run the following code :
var db = Database.Open();
var contact = new Contact() {FirstName = "Mark", LastName = "Rendle"} ;
db.Contacts.Insert(contact);
I get an error :
List initializers must contain at least one initializer
Stack Trace :
at System.Linq.Expressions.Expression.ListInit(NewExpression newExpression, IEnumerable1 initializers)
at Simple.Data.Extensions.ObjectEx.MakeToDictionaryFunc(Type type)
at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)
at Simple.Data.Extensions.ObjectEx.ObjectToDictionary(Object obj)
at Simple.Data.Commands.InsertCommand.InsertEntity(Object entity, DataStrategy dataStrategy, String tableName, ErrorCallback onError, Boolean resultRequired)
at Simple.Data.Commands.InsertCommand.DoInsert(InvokeMemberBinder binder, Object[] args, DataStrategy dataStrategy, String tableName)
at Simple.Data.Commands.InsertCommand.Execute(DataStrategy dataStrategy, DynamicTable table, InvokeMemberBinder binder, Object[] args)
at Simple.Data.DynamicTable.TryInvokeMember(InvokeMemberBinder binder, Object[] args, Object& result)
at Simple.Data.ObjectReference.TryInvokeMember(InvokeMemberBinder binder, Object[] args, Object& result)
at CallSite.Target(Closure , CallSite , Object , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecuteVoid2[T0,T1](CallSite site, T0 arg0, T1 arg1)
at ProjectXBaseDataImporter.DataSaver.PersistContacts(IEnumerable1 contactsx) in c:\Code\XXX\ProjectXBaseDataImporter\ProjectXBaseDataImporter\CSVImporter.cs:line 54
at ProjectXBaseDataImporter.DataImporter.Import[T](String filePath) in c:\Code\XXX\ProjectXBaseDataImporter\ProjectXBaseDataImporter\CSVImporter.cs:line 77
at ProjectXBaseDataImporter.DataImporter_Test.Import() in c:\Code\XXX\ProjectXBaseDataImporter\ProjectXBaseDataImporter\CSVImporter_Test.cs:line 32
Error on my part.
Another Library I am using requires classes to have fields opposed to properties.
I was coding against the fields not properties.

getting Error(There was an error generating the XML document.) fetch data from server side in extjs in asp.net

I am working with Extjs 4.1 and asp.net
I am trying to fill grid panel from database but getting error. I am using webservice to fetch data.
Error:
System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: Cannot serialize the DataTable. DataTable name is not set.
at System.Data.DataTable.WriteXmlSchema(XmlWriter writer, Boolean writeHierarchy)
at System.Data.DataTable.System.Xml.Serialization.IXmlSerializable.WriteXml(XmlWriter writer)
at System.Xml.Serialization.XmlSerializationWriter.WriteSerializable(IXmlSerializable serializable, String name, String ns, Boolean isNullable, Boolean wrapped)
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write2_DataTable(Object o)
at Microsoft.Xml.Serialization.GeneratedAssembly.DataTableSerializer.Serialize(Object objectToSerialize, XmlSerializationWriter writer)
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
--- End of inner exception stack trace ---
at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces)
at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
at System.Web.Services.Protocols.XmlReturnWriter.Write(HttpResponse response, Stream outputStream, Object returnValue)
at System.Web.Services.Protocols.HttpServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream)
at System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues)
at System.Web.Services.Protocols.WebServiceHandler.Invoke()
my webservice code
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json,UseHttpGet = true, XmlSerializeString = false)]
public DataTable displayData() {
db obj = new db();
return obj.getCountry();
}
calling web service from js file
var store = Ext.create('Ext.data.Store', {
pageSize: 20,
model: 'ForumThread',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'report.asmx/displayData',
dataType: "json",
contentType: "application/json; charset=utf-8",
//url: '/grid.json',
reader: {
root: 'data' ,
type: 'json',
method: "GET",
totalProperty: 'totalCount'
}
}
});
even i remove this line from webservice [ScriptMethod(ResponseFormat = ResponseFormat.Json,UseHttpGet = true, XmlSerializeString = false)] but still same error.
I didnt use XMLSerializer in my code then also it will give me error like There was an error generating the XML document.
You need to supply the datatable with a name, as the error suggests.
dt.TableName = "myTable";

Checkbox Helper: Odd string to bool conversion error

I've a web using asp.net MVC 3 with razor.
In one view I'm having an odd error with the checkbox helper.
Here is the razor code:
#Html.CheckBox("rememberPassword", Model.RememberPassword, new { tabindex = "4", style = "width:15px" })
The property in the model (which I set to true in the Model constructor):
public bool RememberPassword { get; set; }
And the logged error:
2012-04-13 01:20:33.334 [13 ] Error - Reference: 0413-012033-334 - Global site error, page: /es/login
System.InvalidOperationException: The parameter conversion from type 'System.String' to type 'System.Boolean' failed. See the inner exception for more information. ---> System.FormatException: -1' is not a valid value for Boolean. ---> System.FormatException: String was not recognized as a valid Boolean.
at System.Boolean.Parse(String value)
at System.ComponentModel.BooleanConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
--- End of inner exception stack trace ---
at System.ComponentModel.BooleanConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType)
--- End of inner exception stack trace ---
at System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType)
at System.Web.Mvc.ValueProviderResult.UnwrapPossibleArrayType(CultureInfo culture, Object value, Type destinationType)
at System.Web.Mvc.ValueProviderResult.ConvertTo(Type type, CultureInfo culture)
at System.Web.Mvc.HtmlHelper.GetModelStateValue(String key, Type destinationType)
at System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper, InputType inputType, ModelMetadata metadata, String name, Object value, Boolean useViewData, Boolean isChecked, Boolean setId, Boolean isExplicitValue, IDictionary`2 htmlAttributes)
at System.Web.Mvc.Html.InputExtensions.CheckBoxHelper(HtmlHelper htmlHelper, ModelMetadata metadata, String name, Nullable`1 isChecked, IDictionary`2 htmlAttributes)
at System.Web.Mvc.Html.InputExtensions.CheckBox(HtmlHelper htmlHelper, String name, Boolean isChecked, Object htmlAttributes)
at ASP._Page_Views_Login_Index_cshtml.Execute() in d:\[...]\Views\Login\Index.cshtml:line 49
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.StartPage.RunPage()
at System.Web.WebPages.StartPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
Why is this happening?
Note:
It keeps getting odder and odder. As magically as the error started appearing (in a productive site some day without any updates or releases) not it has stopped. It's been three days without the error. However, I'd still like to know why was it.
It had nothing to do with the way of creating the checkbox. In some very odd scenarios (which I had forgotten at all), this forms may be submitted (from other sites) without this parameter. In this cases the bool field was trying to obtained from the string "-1".
One way of resolving this issue (that I have discovered to be a good practice) is to avoid "not-nullable" fields in the Model.
Just try this instead
Html.CheckBoxFor(model => model.RememberPassword , chkHtmlAttributes)
And define the chkHtmlAttributes to these
tabindex = "4", style = "width:15px"

Resources