I've been trying to pass a data array to c# web method with using jquery. I have a table which has selectable rows. And my function must pass the id's of selected data. But i can't pass the object array with PageMethods.
Here is my jquery function;
function DeleteQuestions()
{
var table = $('#questTable').DataTable();
var data = (table.rows('.selected').data()).map(function (d) { return d.q_id; });
PageMethods.Delete(data);
}
When i debug it with firebug, veriable data looks like : Object["543","544","546"] as i wanted.
And here is my Web Method:
[WebMethod]
public static void Delete(List<string> questId)
{
DB_UserControl carrier = new DB_UserControl(); //break pointed here
}//and looks it doesn't come here
It doesn't work, and the error is : Cannot serialize object with cyclic reference within child properties. I've searced for error but i couldn't figured it out. So need some help. Thanks in advance.
Note:Error throws at script function's last line: PageMethods.Delete(data);
And i think it might be about mapped data causes some kind of loop behavior.
Problem solved with changing syntax. I use
var data = $.map(table.rows('.selected').data(), function (d) {
return d.q_id;
});
instead of given line. I don't know what caused the error but this code works fine and i get data in c#. Thank you all
Related
I have a hjson file like this that I want to deserialize and work with:
{
"TestConfig": {
"SecondConfig": {
"ConnectionString": "Integrated Security = true; Data Source = dataPseudo; Initial Catalog = catalogPseudo; Connect Timeout = 180",
"SpecificationPseudo": "pseudo",
"NumberOfHintsPseudo": 300
},
"ThirdConfig": "pseudo"
}... // more hjson coming here.
I load it with the HjsonValue.Load method like this:
private static Foo convertJson()
{
var loadedValue = HjsonValue.Load("hjsonFile.hjson").ToString();
return new JsonSerializer<Foo>().DeserializeFromString(loadedValue);
// another failed method: return JsonConvert.DeserializeObject<Foo>(loadedValue);
// A third failed method: return JsonConvert.DeserializeObject<Dictionary<string, Foo>>(loadedValue);
}
I think my problem is in the 2 c#-coded lines, but can't figure what. Am I deserializing wrong or what seems to be the problem? I suspect that it's because it is a nested json, but can't find a way to deserialize it. Trying to use dictionary as it is a answer in a other stack-question, but it didn't work for me.
Note: The first and second tried return method don't return any errors, but they just return a nullreferenceexception since "SecondConfig" and "ThirdConfig" both are null..
Update (with help from er-sho): removed the "root"-element from the hjson (TestConfig), which solved the problem.
Removing "TestConfig" from the hjson fixed it, since it's root and the class I am working with.
I am using Unity WebGL for my project and want to communicate from browser JavaScript to C#. One way is to call C# function from JavaScript using SendMessage. I am easily making call using this code snippet in javascript:
gameInstance.SendMessage("MyObjectName","MyFunctionName",myParameter);
But there is a problem it is not returning any value. For getting a value I have to implement a separate function that run another function. Can I return value directly? Send Message docs clearly stating it don’ t return any value, so other than sendMessage is there any way available to get return value from directly function calling?
Use your custom class as a parameter - for example:
public class CustomData
{
public string Input;
public string Output;
}
...
CustomData data = new CustomData();
data.Input = "Something";
gameInstance.SendMessage("MyObjectName", "MyFunctionName", data);
//use data.Input inside MyFunctionName like a parameter
//change data.Output inside MyFunctionName
//use data.Output
Debug.Log(data.Output);
Am modifying the complex function which is already written where they are using the below code :
private List<string> Values()
{
if (ViewBag.Sample == null)
{
ViewBag.Sample = TestData();
}
}
// where TestData() hits the DB and returns corresponding result
Values() is called multiple places in the same file where this will return by hitting the DB TestData() first time and from next calls it will directly return from ViewBag.
Is this is a good approach ?
What are all the alternative approach we have in MVC to handle this scenario ?As DB hit is a costly call we need to use some other techniques.
Thanks
You could either keep your data in session like this:
Session['*your session key*'] = TestData();
And then retrieve it like this:
var myData = Session['*your session key*'] as YourObject //cast it to an object if you need to.
Or you could use caching:
System.Web.HttpRuntime.Cache[cacheKey] = TestData
And retrieving:
var myData =System.Web.HttpRuntime.Cache[cacheKey] as YourObject
That code should ensure that you only touch the database the first time the method is invoked.
If the same data is used on multiple pages you could also have a lot at the Cache- or Session class.
If size of the data retrieved from database is not very big then you can use Cache
Otherwise you can store data in Session as well.
You have the options to keep the data like Session, Cache.
[OutputCache(Duration = 60)] // Caches for 60 seconds
private List<string> Values()
{
if (ViewBag.Sample == null)
{
ViewBag.Sample = TestData();
}
}
MVC Model Binder
See Sample code
I have an asp.net user control which exposes a public IEnumerable object. This could be converted to a list or array if it helps to answer the question. What I would like to do is to loop through all of the server objects within a javascript function and do something with the contents of each item. I would like to achieve this using inline server tags if possible. Something like the below.
function iterateServerCollection()
{
foreach(<%=PublicCollection %>)
{
var somevalue = <%=PublicCollection.Current.SomeValue %>;
}
}
Is it possible to achieve this?
Managed to achieve what I wanted thanks to the comment from geedubb. Here's what the working javascript looks like.
var myCollection = <%= new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(myCollection) %>;
for(var i in myCollection)
{
var somevalue = myCollection[i].SomeValue;
}
I would do as others have suggested and serialize the object, you could even use an ajax call to grab the data from the start of that function
function iterateServerCollection()
{
//Ajax call to get data from server HttpHandler/WebAPI/Service etc.
for(var item in resultObject) {
//you can use item.WhateverPropertyIsOnObject
}
}
The snippet below is from a Windows 8 store app in c# and xaml.
I have put this code together from variou samples on the web so this may not be the neatest way of doing this. Most of it is from the Grid template supplied in VS2012 and I have hooked up my web api as the source of the data
Please explain the following
When i call the Get method all works fine and i get data back into the xaml view
When i uncomment the Take(10) in the same method i get no data back.
It seems any attempt to put an extension method of a LINQ variety just stops the data being returned and also gives no indication why, it complies fine!
Any help appreciated
Thanks
Mark
public class TeamDataSource
{
private static TeamDataSource _sampleDataSource = new TeamDataSource();
private ObservableCollection<TeamDataItem> _items = new ObservableCollection<TeamDataItem>();
public ObservableCollection<TeamDataItem> Items
{
get { return this._items; }
}
public TeamDataSource()
{
this.Initialize();
}
public static IEnumerable<TeamDataItem> Get()
{
var thisdata = _sampleDataSource.Items;
return thisdata;//.Take(10);
}
private async void Initialize()
{
using (var client = new DataServiceClient())
{
List<TeamDataItem> list = await client.Download<List<TeamDataItem>>("/teams");
foreach (var i in list.OrderByDescending(t => t.Points).ThenByDescending(t => t.GoalDiff))
{
TeamDataItem team = i;
_items.Add(team);
}
}
}
}
Your problem is that Take doesn't immediately enumerate the items. It defers enumeration until either foreach is called on it or GetEnumerator is called on it. In this case the collection it is enumerating is disposed (as soon as the Get content ends) and so when it finally enumerates the items, there are no items anymore. Try adding thisdata.GetEnumerator(); as a line before your return statement.
From here:
This method is implemented by using deferred execution. The immediate
return value is an object that stores all the information that is
required to perform the action. The query represented by this method
is not executed until the object is enumerated either by calling its
GetEnumerator method directly or by using foreach in Visual C# or For
Each in Visual Basic.
Seems it was quite obvious in the end. As I was using aync and await, the call was immediately returning before the data had arrived. Therefore nothing for the Take(4) to work on.
Only problem now is when can i tell the task has completed?