call webmethod with parameter from javascript using Json.Encode - c#

I have a WebMethod:
[WebMethod]
public static string[] getDropDown(int idSpacies)
{
var raceList = from r in db1.breed where r.spaciesID == idSpacies select r;
string[] temp = new string[raceList.Count()];
int counter = 0;
foreach (var item in raceList )
{
temp[counter] = item.name;
counter++;
}
return temp;
}
And JavaScript function:
function changeSpacies()
{
var temp = document.getElementById("selectpicker").value;
var availableTags = #Html.Raw(Json.Encode(AlewetWeb.Areas.ClinicService.Controllers.BreedsController.getDropDown(temp)));
$("#tags").autocomplete({
source: availableTags
});
}
When I use temp variable as parameter in a WebMethod's getDropDown call I receive error
temp doesn't exist in the current context
How I can pass a JavaScript variable to WebMethod.

Related

How to read data from any file and insert to class object using c#

I am reading a data from CSV file and trying to add to object. but when i add new record by looping through records the data in object is getting overridden.
public static void Process()
{
var path= #"ABC.csv";
var header = false;
var lines = System.IO.File.ReadAllLines(filePath);
var element = new List<Content>();
var mapTo = new Content();
for (var i = 0; i < lines.Length; i++)
{
var t = lines[i];
if (!header)
{
header = true;
}
else
{
var data = t.Split(',');
mapTo.Key= data[0];
mapTo.Name= data[1];
mapTo.Number= data[2];
mapTo.Date= data[3];
element.Add(mapTo);
}
}
var result = element;
}
so here when i try to add mapTo to element all the content in element variable is getting overridden.Can anybody suggest what's wrong i am doing here.
Move var mapTo = new Content(); into the for loop. Otherwise you have the same instance of Content for each loop iteration which gets overriden by the assigenments in the for loop.
public static void Process()
{
var path= #"ABC.csv";
var header = false;
var lines = System.IO.File.ReadAllLines(filePath);
var element = new List<Content>();
for (var i = 0; i < lines.Length; i++)
{
var mapTo = new Content(); //here
var t = lines[i];
if (!header)
{
header = true;
}
else
{
var data = t.Split(',');
mapTo.Key= data[0];
mapTo.Name= data[1];
mapTo.Number= data[2];
mapTo.Date= data[3];
element.Add(mapTo);
}
}
var result = element;
}

Get values out of an object into properties of another class

i have a gridview
INSEE1 Commune
------ -------
10002 AILLEVILLE
10003 BRUN
i have a script that return a list of object.
List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1");
my Temp is a list of object of INSSE1 that i have selected.
but now i add Commune also, so my script become:
List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1","Commune");
and my Temp is list of object of INSEE1 and Commune look at image:
how can i acces 10002 and AILLEVILLE ?
i have try with cast it of my Pers_INSEE class:
public class Pers_InseeZone
{
string _Code_Insee;
public string Code_Insee
{
get { return _Code_Insee; }
set { _Code_Insee = value; }
}
string _Commune;
public string Commune
{
get { return _Commune; }
set { _Commune = value; }
}
}
foreach (var oItem in Temp )
{
Pers_InseeZone o = (Pers_InseeZone)oItem;
}
but I not work, I can not cast it.
I have tried like this:
foreach (var oItem in Temp )
{
var myTempArray = oItem as IEnumerable;
foreach (var oItem2 in myTempArray)
{
string res= oItem2.ToString();
....
the value of res = 10002, but how can I get the value of AILEVILLE ?
the value of Temp[0].GetType(); is:
Thanks in advance
Ok I thought so, so as already mentioned in the comments you have a array of objects inside each object so you need to cast first every object in your list into an array of objects: object[] then you can access each part. Here is an example that recreates your problem:
object[] array = new object[] {10002, "AILEEVILLE"};
List<object> Temp = new List<object> {array};
And the solution:
// cast here so that the compiler knows that it can be indexed
object [] obj_array = Temp[0] as object[];
List<Pers_InseeZone> persList = new List<Pers_InseeZone>();
Pers_InseeZone p = new Pers_InseeZone()
{
Code_Insee = obj_array[0].ToString(),
Commune = obj_array[1].ToString()
};
persList.Add(p);
Applied to your code it would look something like this:
List<object> Temp = ASPxGridView_Insee.GetSelectedFieldValues("INSEE1","Commune");
List<Pers_InseeZone> persList = new List<Pers_InseeZone>();
foreach (object oItem in Temp )
{
object [] obj_array = oItem as object[];
Pers_InseeZone p = new Pers_InseeZone()
{
Code_Insee = obj_array[0].ToString(),
Commune = obj_array[1].ToString()
};
persList.Add(p);
}
The problem is down to the fact your class doesn't match the same structure as the data you are getting, so it can't be cast into it.
Instead why don't you just iterate over the results and build a new instance of the class?
var tempList = new List<Pers_InseeZone>();
foreach (var oItem in Temp)
{
tempList.Add(new Pers_InseeZone(oItem[0], oItem[1]));
}
You will need to add a constructor to your Pers_InseeZone class, and assign the variables there.

C#: How to using global variable with Javascript

everyone!
I'm learning ASP.NET MVC and have some question.
My problem is Passing Data from View to Controller.
This my Code:
#{
string listID = "";
}
and I try to use this variable:
function SubmitDelete() {
var listId = "";
var x = document.getElementsByName("IsCheck");
for (var i = 0; i < x.length; i++) {
if (x[i].checked == true) {
listId += x[i].value + ", ";
};
}
#listID = listId;
return listId;
}
Finalize, I want to pass #listID to Controller:
#using (Html.BeginForm("DeleteChecked", "Category", new { listID }, FormMethod.Post)){ }
It is simple problem about multi delete with checkbox.
Help me, please.
You cannot pass a javascript variable to your controller.
But you can post it as part form data with the help of hidden field.
Better add a hidden field and set it in a Javascript and post
#using (Html.BeginForm("DeleteChecked", "Category", FormMethod.Post)){
Html.HiddenFieldFor(m=>m.MyList, new {#id="my-list-data"})
..other controls and your submit button
}
In a Javascript
function SubmitDelete() {
var listId = "";
var x = document.getElementsByName("IsCheck");
for (var i = 0; i < x.length; i++) {
if (x[i].checked == true) {
listId += x[i].value + ", ";
};
}
$('#my-list-data').val(listId);
}
You cannot do that.
The aspx\ascx\cshtml etc. page is built in the server side while the js is computed on the client's side.
You can add C# string to js functions but they will be hard coded when they get to the client.
All the C# expression are evaluated before they get to the client and before the js is computed.
Here's an example:
This is what you see on the aspx\ascx\cshtml file.
<%
string str = 'test';
%>
function jsFunc(){
var myVar = '<%=str%>';
}
This is what the client gets:
function jsFunc(){
var myVar = 'test';
}

What´s the better way to get ID from lookup field value programmatically?

When I try to get the id from:
string idValue = item[Lookup].ToString();
I get the next value by example:
1;#1
I need the value this way:
1
Actually this code handle the requirement:
using (SPSite site = new SPSite(context.CurrentWebUrl))
{
using (SPWeb web = site.OpenWeb())
{
//Context list
SPList list = web.Lists[context.ListId];
SPList child = web.Lists[List];
SPListItem currentItem = list.GetItemById(context.ItemId);
string updateItems = "";
int ID = currentItem.ID;
foreach (SPListItem item in child.Items)
{
string idValue = item[Lookup].ToString();
int partial = idValue.LastIndexOf(";");
string idPure = idValue.Substring(0, partial);
if (idPure == ID.ToString())
{
item[Field] = Value;
item.Update();
updateItems += item.ID.ToString();
}
}
//Return Items*/
results["Items"] = updateItems;
SPWorkflow.CreateHistoryEvent(web, context.WorkflowInstanceId, 0,
web.CurrentUser, TimeSpan.Zero, "Information",
"Event from sandboxed, updates: " + updateItems, string.Empty);
}
}
I want to know a better function or property to get the ID from lookup field.
SPFieldLookupValue fieldLookupValue = new SPFieldLookupValue(item["FieldName"].ToString());
int lookupID = fieldLookupValue.LookupId;
Here you go :)
SPList mySPList = oWeb.Lists["ProjectList"];
newItem["LookupFieldName"] = new SPFieldLookupValue(getLookUp(mySPList,LookupFieldValue), LookupFieldValue);
public static int getLookUp(SPList oList, string FieldValue, string sFieldName="Title")
{
foreach (SPListItem spi in oList.GetItems())
{
if (spi[sFieldName].ToString() == FieldValue)
{
return spi.ID;
}
}
return 0;
}
i can set lookup field in SharePoint by use this code
<script>
window.onload = (event) => {
document.getElementById("tafahomNameId_78ec7c44-beab-40de-9326-095f474519f4_$LookupField").value = 1;
};
</script>

result shows System.String[]

On my GetBusiness.aspx page i have create a test list
List<string> l = new List<string>();
l.Add("one");
l.Add("two");
l.Add("three");
l.Add("four");
l.Add("five");
// B.
string[] s = l.ToArray();
Response.Write(s);
No on my second page(default aspx page) I have some jQuery to load this array and show the results:
$.get('GetBusiness.aspx', function (returndata) {
// for each address in returndata
alert(returndata);
but the result is : System.String[]
If I iterate , he iterate the string "System.String[]"
$.each(returndata, function (index, value) {
alert(index + ': ' + value);
};
How can I show the results from the string array?
Change Response.Write(s) to :
JavaScriptSerializer objSerializer = new JavaScriptSerializer();
Response.Write(objSerializer.Serialize(s));
Reference: JavaScriptSerializer
In your GetBusiness page, you are outputting the .ToString() property of the array, which is "System.String[]". You need to iterate the list and output each element separatly in some usable format, like JSON and then parse appropriately.
Example (untested):
string reponse = "";
response += "{ \"Output\":[";
for(int i = 0; i < s.Length; i++) {
response += s[i];
if (i < s.Length - 1) response += ", "
}
response += "] }";
Response.Write(response);
List<string> l = new List<string>();
l.Add("one");
l.Add("two");
l.Add("three");
l.Add("four");
l.Add("five");
// B.
string[] s = l.ToArray();
Response.Write(string.Join(",", s));
javascript:
$.get('GetBusiness.aspx', function(returndata) {
var arr = returndata.split(',');
$.each(arr, function(index, value) {
alert(index + ': ' + value);
});
});

Categories

Resources