Web API MVC get query parameter from ng-table? - javascript

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>

Related

jQuery: How to traverse / Iterate over a list of object

I'm using asp.net MVC4 for web app development.
I would like to traverse a list of objects from a ViewModel.
Below is the class of the object:
public class User
{
public int Id {get; set;}
public string Name {get; set;}
public string Address {get; set;}
public string Department {get; set;}
}
Below is my ViewModel class:
public class UserViewModel
{
public List<User> AllUsers {get; set;}
public bool IsDeleted {get; set;}
}
As seen in the UserViewModel class, I have a list of objects of type User. Now i would like to iterate through each of the user object in AllUsers list using Jquery and fetch data from them.
In order to do so, I tried doing something like the following:
$(#Model.AllUsers).each( function(){ .... });
I have tried different combination using the above approach, but couldn't succeed. Can anyone suggest a solution for the same.
Thanks in advance.
Assign your collection to a javascript variable using
var users = #Html.Raw(Json.Encode(Model.AllUsers))
which you can then iterate over
$.each(users, function(index, item) {
// access the properties of each user
var id = item.Id;
var name = item.Name;
....
});
<script type="text/javascript">
var UsersList = #Html.Raw(Json.Encode(Model.AllUsers))
for (var i = 0; i < UsersList.length; i++) {
alert(UsersList[i].Id);
alert(UsersList[i].Name);
}
</script>
JavaScript generally is unhappy with razor components although if the above is part of an CSHTML file it will work.
The other approaches are:
Display the collection using razor #foreach ...
Pass the collection as a parameter from you webpage into a JavaScript function on some event
How are you calling this function and what does it do?
In My Case, I fixed by this way :
#for(int i=0;i<Model.AllUsers.Count;i++)
{
#: var name = '#Html.Raw(#Model.AllUsers[i].Name)';
#:alert(name);
}

How do I use JObject if the names are slightly different?

I have a JObject from JSON.NET with the following:
var jOBject = {"schedule.ID" : 1, "schedule.Name" : "NameSchedule"}
The above is what I get from using Javascript to return the ID's and values of textboxes in the MVC Form in my View.
In my controller using C#, I would like to convert it into a Schedule Object that has the following Properties:
public class Schedule {
public int ID {get;set;}
public string Name {get;set;}
}
I cannot do a
Schedule sched = jsonObject.toObject<Schedule>();
because the names are slightly different as the properties on the Jobject is prepended with 'schedule'.
Is there a query or a way to do the conversion that allows me to remove the 'schedule' in the jsonObject such that I can do the simple conversion in one line?
One simple way to get it working is to use the JsonProperty attribute to specify what JSON key you want to map to a certain C# property:
public class Schedule
{
[JsonProperty("schedule.ID")]
public int ID {get;set;}
[JsonProperty("schedule.Name")]
public string Name {get;set;}
}
Then you can just use JsonConvert.DeserializeObject to deserialize your JSON into a Schedule instance:
var schedule = JsonConvert.DeserializeObject<Schedule>(json);
Example: https://dotnetfiddle.net/Nml9be
To use different key names in the JSON, you can decorate your C# class with DataContract and DataMember attributes.
[DataContract]
public class Schedule {
[DataMember("schedule.ID")]
public int ID { get; set; }
[DataMember("schedule.Name")]
public string Name { get; set; }
}
JObject scheduleObj={schedule:{"ID" : 1, "Name" : "NameSchedule"}}
JsonSerializer seria = new JsonSerializer();
Schedule oSchedule = new Schedule();
if (ScheduleObj["Schedule"] != null)
{
oSchedule = (Schedule)seria.Deserialize(new JTokenReader(ScheduleObj["Schedule"]), typeof(Schedule));
}

Creating c# array similar to javascript array

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.

Error deserializing JSON data to Dictionary <string, string>

Here is the JSON that I want to deserialize into Dictionary using native Javascript support.
string data = "{"Symptom":[true,true,true],"Action":[true,true],"AllArea":true}";
But when I attempt to deserialize using below code
Dictionary values = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize>(data);
It gives me an error stating
"Type 'System.String' is not supported for deserialization of an array"
I am using .Net Framework 3.5. Please help me getting this done.
i guess you can not convert that to a dictionary directly... i think deserializer needs a corresponding type, with intelligible property names with type,
i think you can convert to a type, then generate your dictionary, something like:
public class MyClass
{
public List<bool> Symptom { get; set; }
public List<bool> Action { get; set; }
public bool AllArea { get; set; }
public Dictionary<string, List<bool>> getDic()
{
// this is for example, and many many different may be implement
// maybe some `reflection` for add property dynamically or ...
var oDic = new Dictionary<string, List<bool>>();
oDic.Add("Symptom", this.Symptom);
oDic.Add("Action", this.Action);
oDic.Add("AllArea", new List<bool>() { AllArea });
return oDic;
}
}
then:
string data = "{\"Symptom\":[true,true,true],\"Action\":[true,true],\"AllArea\":true}";
System.Web.Script.Serialization.JavaScriptSerializer aa = new System.Web.Script.Serialization.JavaScriptSerializer();
var o = aa.Deserialize<MyClass>(data);
var dic = o.getDic();
anyhow, it was a good question

How to escape string within razor?

I have a listbox that I am populating using a foreach. (Long explanation of why I need to do this.)
I need to escape the string because fname and lname can contain special characters, like ' or ".
foreach (var cust in item.Customers)
{
var custString = string.Format("{0}%#%{1}%#%{2}", cust.CustID, cust.LName, cust.FName);
<option value="#custString">#cust.DisplayName</option>
}
Is there any way to do a javascript escape of custString right after setting the value? Or is there there a preferred C# way of escaping that will work well with javascript's unescape, which I am using to unescape these chars.
That's what the AttributeEncode helper does:
<option value="#Html.AttributeEncode(custString)">#cust.DisplayName</option>
But hey, what are you doing? foreach loop to generate a dropdown list????
Try the Html.DropDownListFor helper and stop the bleeding inside your view before its too late. This helper does what its name suggests. And takes care of encoding and escaping and whatever.
So simply define a view model:
public class MyViewModel
{
public string CustomerId { get; set; }
public IEnumerable<SelectListItem> Customers { get; set; }
}
then go ahead and have your controller action populate and pass this view model to the view:
public ActionResult Index()
{
IEnumerable<Customer> customers = ... fetch the domain model from your DAL or something
// map to a view model:
var viewModel = new MyViewModel
{
Customers = customers.Select(x => new SelectListItem
{
Value = x.CustID,
Text = string.Format("{0}%#%{1}%#%{2}", x.CustID, x.LName, x.FName)
})
};
// pass the view model to the view:
return View(viewModel);
}
and inside the view, use the DropDownListFor helper when you need to generate a dropdown list:
#Html.DropDownListFor(x => x.CustomerId, Model.Customers)

Categories