I have JS function like this inside the #section Scripts of .cshtml view:
function SendIndexes() {
var selectedSortOption = $("#SortBy").find('option:selected');
var sortIndex = selectedSortOption.val();
var selectedFilterByTypeOption = $("#filter_marker_bytype").find('option:selected');
var filterByTypeIndex = selectedFilterByTypeOption.val();
var selectedFilterByScoreOption = $("#filter_marker_byscore").find('option:selected');
var filterByScoreIndex = selectedFilterByScoreOption.val();
var selectedFilterByStatusOption = $("#filter_marker_bystatus").find('option:selected');
var filterByStatusIndex = selectedFilterByStatusOption.val();
var markerFilterIndexes = [filterByTypeIndex, filterByScoreIndex, filterByStatusIndex];
location.href = `/Markers/MarkersList?page=#Model.PagingInfo.CurrentPage&sortIndex=${sortIndex}&markerFilterIndexes=${markerFilterIndexes}`
}
and the controller action signature like this:
public async Task<IActionResult> MarkersList(List<string> markersForUpdateIds, IEnumerable<int> markerFilterIndexes, int page = 1, string message = "", int sortIndex = 0)
{
...
}
The problem is that the array of three elements is not passed at all. However, if I only push a single variable (element) to this array, then it is passed to the controller's action as it should.
Why is this happening and how to have all three elements passed to the controller?
I'll suggest you to use [FromQuery] attribute in your parameter and format your URL like this: myparam=myvalue1&myparam=value2&myparam=myvalue3.
public async Task<IActionResult> MarkersList([FromQuery]List<string> markersForUpdateIds, [FromQuery]IEnumerable<int> markerFilterIndexes, [FromQuery]int page = 1,[FromQuery] [FromQuery]string message = "", [FromQuery]int sortIndex = 0)
{
...
}
Take a look of ModelBinding:
https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1#sources
For passing an array to the controller action. Data formats that use subscript numbers (... [0] ... [1] ...) must ensure that they are numbered sequentially starting at zero. Here you don't need to define an array, just format your url like this:
location.href = `/Markers/MarkersList?page=#Model.PagingInfo.CurrentPage&sortIndex=${sortIndex}&markerFilterIndexes[0]=${filterByTypeIndex}&markerFilterIndexes[1]=${filterByScoreIndex}&markerFilterIndexes[2]=${filterByStatusIndex}`
Since the data in the array is just int type data, you can omit the subscript numbers.
Related
I'm sending string array to my controller that contains array of Ids in it.
function submit(){
var ids = [];
bootbox.confirm("Are you sure to send data?", function(confirmed){
if(confirmed){
$('input[id^="tdCheckbox_"]').each(
function () {
var $this = $(this);
if($this.is(":checked")){
ids.push($this.attr("id").replace("tdCheckbox_",""));
}
}
);
$("#Ids").val(ids);
$("#submitForm").submit();
}
});
}
<g:formRemote name="submitForm" url="[controller:'myController', action:'submit']" onSuccess="removeIds(data)">
<g:hiddenField name="Ids" />
</g:formRemote>
CONTROLLER:
def submit(){
def result = [success:false]
if(params?.Ids){
String[] ids = params?.Ids
ids.eachWithIndex{ it, int i ->
//HERE OUTPUT IS LIKE
//4
//,
//5
//,
//6
println(it.value)
}
result["id"] = params?.Ids
}
render result as JSON
}
In eachWithIndex loop i'm getting output with , (comma) that I do not require, I think there must be a good option to loop through it.
Please suggest the same.
problem that you submitting from javascript one string value (ids delimited with coma)
ids=1,2,33
and on the level of groovy/grails the params?.Ids returns you just a String like this: "1,2,33"
and assigning a String to a String[] just splits it by chars...
as workaround in groovy you can use params?.Ids?.split(',')
String[] ids = "1,2,33".split(',')
or submit multiple values form javascript like this:
ids=1 & ids=2 & ids=33
in this case grails will return you an array for params?.Ids expression if more then one value submitted with the same name
I have created a WinRT component in C# which accepts a IEnumarable as a parameter
C#
public sealed class MyClass
{
public IEnumarable<DtoClass> MyFunction(IEnumarable<DtoClass> properties) {
return properties;
}
}
Java script
var Test=[];
for (var i = 0; i < res1.length; i++)
{
Test.push({ category_id: res1[i].category_id });
}
var Conncetion = WindowsRTSqlite.MyClass();
var result = Conncetion.MyFunction(Test);
I'm returning the same input parameters which I'm sending to MyFunction method but it's not return any result. I am not sure why this is not working. Any Ideas?
Thanks in advance.
How to pass list of object from JavaScript to Windows Runtime Component C#?
Actually the correct way is to serialize the collection to a json string and pass this string to the Windows Runtime Component. And deserialize the json string in the runtime component side for data dealing. After that return back the serialized json string to JavaScript uwp app. For how to serialize in JavaScript please reference this class, for how to serialize in C# you can reference this namespcase. So your code on the JavaScript side may as follows:
var Test = [];
for (var i = 1; i < 6; i++) {
Test.push({ category_id: i });
}
var Conncetion = RuntimeComponent1.MyClass();
var Testserialation = JSON.stringify(Test);
var resultnew = Conncetion.newFunction(Testserialation);
var Testreturn = JSON.parse(resultnew);
And in windows runtime component:
public sealed class MyClass
{
public string NewFunction(string jsonstring)
{
JsonArray entity= JsonArray.Parse(jsonstring);
return entity.ToString();
}
}
I am not sure why this is not working.
According to your code snippet, you created an object array and trying to pass it to the runtime component as IEnumarable<DtoClass>. You passed an array, in my opinion you should be able receive it as an array. And I don't think object can be parsed to DtoClass automatically. If you use a string or int array that can be recognized. For example , an int array:
var newTest = [1, 2, 3, 4];
var result2 = Conncetion.changeArray(newTest);
Code in component:
public int[] ChangeArray([ReadOnlyArray()] int[] input)
{
int[] output =(int[])input.Clone();
// Manipulate the copy.
// ...
return output;
}
More details about passing arrays to a Windows Runtime Component please reference this article.
I want to pass array (2 dimension) from controller to javascript variable. I use session to pass but this not work. In javascript code I use like this:
var data = '<%= Session["LatLon"] %>';
when run project and use inspect element, there is in data :
how to pass? Can i Pass array with 2 dim with session?
When inserting the value into Session["LatLon"], save it as JSON instead of a C# string array.
string[][] mystringarr = ...
Session["LatLon"] = JsonConvert.SerializeObject(mystringarr);
And in the view use
var data = <%= Session["LatLon"] %>;
So it will generate something like
var data = [["1.0", "1.4"], ["4.6","4.8"]];
Using JSON.NET
http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonConvert_SerializeObject.htm
What you are currently observing is a result of execution .ToString method of Session["LetLon"] object.
What you intent to receive is var data = [[1, 2], [3, 4]];.
So you can simply write a correct stringification of your two-dimensional array. I suggest to write simple extension method:
public static string ToJsString(this string[,] array) {
return Enumerable.Range(0, array.GetLength(0))
.Aggregate(new StringBuilder(),
(sbi, i) => sbi.AppendFormat(i == 0 ? "{0}" : ", {0}",
Enumerable.Range(0, array.GetLength(1))
.Aggregate(new StringBuilder(),
(sbj, j) => sbj.AppendFormat(j == 0 ? "{0}" : ", {0}", array[i,j]),
sbj => string.Format("[{0}]", sbj))),
sb => string.Format("[{0}]", sb));
}
In order to use it write then var data = <%= ((string[,])Session["LatLon"]).ToJsString() %>.
I need to build a string like "1-2-3-4-5", from an IList< int > returned by an MVC Action.
Action:
public virtual JsonResult AdvancedSearch(AdAdvancedSearchViewModel asViewModel)
{
IList<int> adIds = new List<int>();
try
{
var asDto = Mapper.Map<AdAdvancedSearchViewModel, AdAdvancedSearchDto>(asViewModel);
adIds = _adService.AdvancedSearch(asDto);
}
catch
{
adIds = null;
}
return Json(adIds);
}
Javascript function that processes the result:
function onAdAdvancedSearchSuccess(jsonAdListIds)
{
$("#adAdvancedSearchListForm #ids").val(jsonAdListIds);
}
The problem is that I get a string like this "[1,2,3,4]" in the "#adAdvancedSearchListForm #ids" HTML input, and I need to get "1-2-3-4", any idea?
Thanks.
If you want to do it at the client side, simply iterate throught the result array and build the string you want.
$.getJSON("yourURL", { Name: "John", Loc: "2pm" },function(result){
var str="";
$.each(result,function(i,item){
str=str+"-"+item;
});
alert(str);
});
Assuming Name and Loc are the properties of your viewmodel.
If you want to do it on the server side, you may use String.Join method to build the string representation you want. You may need to update the return type of your action method.
public string AdvancedSearch(AdAdvancedSearchViewModel asViewModel)
{
List<int> adIds = new List<int>();
//fill the list
var resutlStr= String.Join("-",adIds.ToArray());
return resutlStr;
}
I prefer to keep my action method returns JSON result instead of this string represetnation because an action method which returns JSON can be used in many places compared to this concrete string return implementation.
AJAX is returning an array which is expected since you are converting a list.
Try parsing the array into the string:
var r = jsonAdListIds[0];
for (var i = 1; i < jsonAdListIds.length; i++) {
r += '-' + jsonAdListIds[i];
}
so I have a WCF service that returns a list of objects of a class , that has been defined in my WCF's contract and I am supposed to receive the Json object in a Javascript Win 8 app. Now when I do
WinJS.xhr({ url: url_final }).then(function (r) {
var result = JSON.parse(r.responseText);
document.getElementById("greetingOutput").innerText = result;
}
I can see [object Object] in that div ,
any idea how do i see individual elements over there ?
My class is :
public class GraphData
{
String concerneddate = String.Empty;
Int32 houroftheday = 0;
Int32 countathour = 0;
}
this line:
var result = JSON.parse(r.responseText);
makes result a javascript object. now u can get individual properties of that object like that:
result.concerneddate;
result.houroftheday;
result.countathour;
I suggest you log the actual result and see the structure of the object.
UPDATE:
after seeing your comment, the way to access the properties would be:
var resultsArray = result.GetGraphDetailsResult;
for (var i in resultsArray){
var ConcernedDate = resultsArray[i].ConcernedDate;
var CountAtHour = resultsArray[i].CountAtHour;
...
}