When I send data (values and dates) from function (hard coded), everything is ok, json file is populated, and I see the chart, but when I send data from database, there is no chart but I see that json file is also populeted.
Here is code:
public class YearlyStat
{
public string year { get; set; }
public double value { get; set; }
}
public ActionResult Statistics(int? id)
{
//var result = db.pricepoints.Where(r => r.commodityID.Equals(id));
var items = from item in db.pricepoints
where (item.commodityID == id)
select item;
var stats = new List<YearlyStat>();
foreach (var item in items)
{
stats.Add(new YearlyStat
{
year = item.date_of_price.ToShortDateString(),
value = item.value
});
}
//but this works
//string s = "2.2.2002";
//double v = 20.20;
//stats.Add(new YearlyStat { year = s, value = v });
//or
//stats.Add(new YearlyStat { year = "2.2.2002", value = 20.20 });
return Json(stats, JsonRequestBehavior.AllowGet);
}
Types are string and double in both cases.
Check your javascript file. Probably is missing the parameter id. If you are using ajax take a look at the parameters ;)
Related
I've been trying to get ng-table(angular directive) work with a web api (ASP.NET MVC). I can load and page the data but the sorting or filtering won't work.
The weird thing is that the sorting or filtering will look like this in the URL:
http://localhost:46278/api/rating?count=10&filter%5Brating.name%5D=fs&page=1&sorting%5Brating.description%5D=asc
If you would "format" it, it would look like this:
filter[rating.name] = fs
sorting[rating.description] = asc
I tried to get them with a string array or a dictionary (KeyValuePair)
But I can't get the values. So I can never filter or sort the data.
I hope you can give me some advice! I appreciate your help!
I wrote a helper class to deal with this. The URL isn't formatted in a way WebAPI expects, so couldn't get the ModelBinder to parse it automatically.
From your controller, call the helpers and provide the entire URL:
// Parse sortings
var sortings = TableHelpers.ParseSortings(Request.RequestUri).ToList();
// Parse filters
var filters = TableHelpers.ParseFilters(Request.RequestUri).ToList();
And the helper class
public static class TableHelpers
{
public static IEnumerable<TableSorting> ParseSortings(Uri requestUri)
{
var regex = new Regex("sorting%5B(.+?)%5D=(asc|desc)");
var matches = regex.Matches(requestUri.AbsoluteUri);
return from Match match in matches
select new TableSorting {Field = match.Groups[1].Value, Order = match.Groups[2].Value};
}
public static IEnumerable<TableFilter> ParseFilters(Uri requestUri)
{
var regex = new Regex("filter%5B(.+?)%5D=(.+?)(?:&|\\z)");
var matches = regex.Matches(requestUri.AbsoluteUri);
return from Match match in matches
select new TableFilter {Field = match.Groups[1].Value, Value = match.Groups[2].Value};
}
}
public class TableSorting
{
public string Field { get; set; }
public string Order { get; set; }
}
public class TableFilter
{
public string Field { get; set; }
public string Value { get; set; }
}
are you asking about directive syntax or your api?
in ng-table directive, insert in <td> tag sorting or/and filtering attrs, like:
<td width="10%" data-title="'NUM'|translate" filter="{ 'num': 'text' }" sortable="'num'"><span>{{item.num}}</span></td>
I am new to MVC and trying to build put a simple web application.
I have a Class - ListItems
public class ListItems
{
public string Display { get; set; }
public string Value { get; set; }
public string Area { get; set; }
public string LongDescription { get; set; }
}
From controller -
I am using function to populate values of dropdownlist .Data is populated to ListItems
List<ListItems> Lst= new List<ListItems>();
string query = #"SELECT DISTINCT A.[COLA],A.[COLB],[COLC] FROM tableA ";
getting to Dataset ds
ListItems item;
foreach (DataRow row in ds.Tables[0].Rows)
{
item = new ListItems();
item.Value = DBBase.ConvertToString(row["COLA"], string.Empty);
item.Display = DBBase.ConvertToString(row["COLB"], string.Empty);
item.Area = DBBase.ConvertToString(row["COLC"], string.Empty);
statusList.Add(item);
}
In View
#Html.DropDownListFor(model => model.COLA, new SelectList(Model.VenueList, "Value", "Display","Area"), "- Please select a Value-", new { id = "lstA" })
Now, I need to get value of 'Area' Column of dropdownlist 'lstA' in javascript
on button click
In javascript
function AB(){
$('#lstVenue :selected').val(); // this gives selected value
}
How to get value of column 'Area' ?
Since a dropdown list cannot bind 3 values, you have to set Value and Area to values of options with a unique character (I used '#' as an example) like this:
// Make sure '#' doesn't appear on "Value" nor "Area"
#Html.DropDownListFor(model => model.COLA, new SelectList(Model.VenueList.Select(v => new { Display = v.Display, Value = string.Concat(v.Value, "#", v.Area) }), "Value", "Display"), "- Please select a Value-", new { id = "lstA" })
Then, you can get both "Value" and "Area" with JavaScript(jQuery) like this:
var selected = $('#lstA :selected').val();
var splited = selected.split("#");
var value = splited[0];
var area = splited[1];
if (area == "0"){
// Do something
}
When I send data (values and dates) from function (hard coded), everything is ok, json file is populated, and I see the chart, but when I send data from database, there is no chart but I see that json file is also populeted.
Here is code:
public class YearlyStat
{
public string year { get; set; }
public double value { get; set; }
}
public ActionResult Statistics(int? id)
{
//var result = db.pricepoints.Where(r => r.commodityID.Equals(id));
var items = from item in db.pricepoints
where (item.commodityID == id)
select item;
var stats = new List<YearlyStat>();
foreach (var item in items)
{
stats.Add(new YearlyStat
{
year = item.date_of_price.ToShortDateString(),
value = item.value
});
}
//but this works
//string s = "2.2.2002";
//double v = 20.20;
//stats.Add(new YearlyStat { year = s, value = v });
//or
//stats.Add(new YearlyStat { year = "2.2.2002", value = 20.20 });
return Json(stats, JsonRequestBehavior.AllowGet);
}
Types are string and double in both cases.
I get it :D
Problem is in my JavaScript, i didn't send 'id' parametar to Statistics function.
<script type="text/javascript">
$.get('#Url.Action("Statistics")', function(result){
new Morris.Line({
// ID of the element in which to draw the chart.
element: 'myfirstchart',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data:
result
,
// The name of the data record attribute that contains x-values.
xkey: 'year',
// A list of names of data record attributes that contain y-values.
ykeys: ['value'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['Value','Date']
});
});
It works when i put:
#Url.Action("Statistics", new { id = ViewBag.commodityID })
Now im happy man :D
I am new in C# and would like to know if it's possible to create an array in C# like following:
rates[0]['logic_id'] = 12;
rates[0]['line_id'] = ""
rates[0]['rate'] = rateVal;
rates[0]['changed'] = isChanged;
rates[1]['logic_id'] = 13;
rates[1]['line_id'] = ""
rates[1]['rate'] = secvalue;
rates[1]['changed'] = isChanged;
Can I create rates array in C# with such values?
EDIT:
My goal is to send rates array to a specific Web API service that is running with PHP. They accept only array with abovementioned structure. That's why I want to achieve that.
The best approach here would be to create a Rate class that is held in a List<Rate>().
public class Rate
{
public int LogicId { get; set; }
public string LineId { get; set; }
public decimal Rate { get; set; }
public bool IsChanged { get; set; }
}
public void Populate()
{
var rates = new List<Rate>();
var rate = new Rate();
rate.LogicId = 12;
rate.LineId = string.Empty;
rate.Rate = 0;
rate.IsChanged = true;
rates.Add(rate);
}
To access the values, you can loop through them:
foreach(var rate in rates)
{
//Do something with the object, like writing some values to the Console
Console.WriteLine(rate.LogicId);
Console.WriteLine(rate.Rate);
}
You could solve it using arrays, but it's someway outdated the approach.
My suggestion is that you should use a List<Dictionary<string, object>>:
var data = new List<Dictionary<string, object>>();
data.Add(new Dictionary<string, object>());
data[0].Add("rate", rateVal);
And later you can access it like JavaScript using dictionary's indexer:
var rate = data[0]["rate"];
Update
OP said:
My goal is to send rates array to a specific Web API service that is
running with PHP. They accept only array with abovementioned
structure. That's why I want to achieve that.
No problem. If you serialize that list of dictionaries using JSON.NET, you can produce a JSON which will contain an array of objects:
[{ "rate": 2 }, { "rate": 338 }]
Actually, .NET List<T> is serialized as a JSON array and a Dictionary<TKey, TValue> is serialized as a JSON object, or in other words, as an associative array.
This can depend on your specific neeeds, mut maybe you just want a list of objects
first create a class:
class Rate
{
public int LoginId { get; set; }
public int? LineId { get; set; }
public decimal RateValue { get; set; }
public bool IsChanged { get; set; }
}
Then, in any method you want, just use:
List<Rate> Rates = new List<Rate>();
Rates.Add(new Rate() {LoginId = 1, LineId = null, RateValue = Rateval, IsChanged = false});
Rates.Add(new Rate() {LoginId = 13, LineId = null, RateValue = SecVal, IsChanged = false});
EDIT
My apologies for the terrible answer, edited to account for the errors
public struct Rate
{
public int LoginId ;
public int LineId ;
public double RateValue ;
public bool IsChanged;
}
public static void makelist()
{
List<Rate> Rates = new List<Rate>();
Rates.Add(new Rate() {LoginId = 1, LineId = null, RateValue = Rateval,IsChanged = false});
}
This method will only hold data, and not hold methods like a class.
With the data types defined in the struct, memory usage stays low as its only purpose is to store data. This is a midway between a variable and a class.
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];
}