How do i show enum value using AngularJs - angularjs

I have created an enum in my mode.
public enum Color
{
Green,
Black,
Red,
Silver,
Yellow,
White,
Grey,
}
I used thus enum in my main class.
public class MotorDetails
{
public int Id { get; set; }
public string Name { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string Year { get; set; }
public string Kilometers { get; set; }
public Color Color { get; set; }
}
I then seed data like
context.MotorDetails.AddOrUpdate(x => x.Id, new MotorDetails()
{
Name = "Accord",
Make = "Honda",
Model = "Accord",
Year = r.Next(1980,2016).ToString(),
Kilometers = r.Next(50000, 200000).ToString(),
Color = (Color)r.Next(1,7),
}
So,in database any value b/w 1,7 is saved for color. Which is fine.
Now i am return this data to my view from controller
public List<MotorDetails> getByMake(string make, int minPrice, int maxPrice)
{
List<MotorDetails> motor = db.MotorDetails.Where(x => x.Make == make && x.Price >= minPrice && x.Price <= maxPrice).ToList();
return motor;
}
Problem:
It returns an integer for color to my view and hence number is showing on view.
I want to show color name for given number.
I am using angularJs and here is my code.
<div>
<table class="table">
<tr>
<th>Name</th>
<th>Make</th>
<th>Model</th>
<th>Year</th>
<th>Kilometers</th>
<th>Price</th>
<th>Color</th>
</tr>
<tr ng-repeat="m in motors">
<td>{{m.Name}}</td>
<td>{{m.Make}}</td>
<td>{{m.Model}}</td>
<td>{{m.Year}}</td>
<td>{{m.Kilometers}}</td>
<td>{{m.Price}}</td>
<td>{{m.Color}}</td>
</tr>
</table>
</div>

JSON.NET (the default json serializer for ASP.NET) has an attribute for this [JsonConverter(typeof(StringEnumConverter))]
So
public class MotorDetails
{
public int Id { get; set; }
public string Name { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public string Year { get; set; }
public string Kilometers { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public Color Color { get; set; }
}
Will serialize the Color as the string value.

I handle this by having a similar object on the client that represents the enum on the server.
Something like:
vm.lookups.colors = [];
vm.lookups.colors.push({ id: 1, value: 'Green' });
vm.lookups.colors.push({ id: 2, value: 'Black' });
// etc.
Then in my view I will render a select and bing the ng-model of the select to the value from the server:
<select ng-options="color.id as color.value for color in vm.lookups.colors"
ng-model="m.Color" disabled>
</select>

An alternative to adding the [JsonConverter(typeof(StringEnumConverter))] attribute on your model property is to add a formatter in your WebApiConfig:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());

Not sure if this is still of interest. I solved this problem differently:
1) Load json data just as before. Serialize enums as Integers, not as strings.
2) Load list of enums as pairs of {Id, Name} from an ApiController. The Name properties are filled with language-specific strings.
3) Lookup the localized Name for each enum Id in the list by a simple javascript method call to your AngularJS controller. (Alternatively you could use a filter here, but thats up to you)
4) Hookup the $rootScope.$On('translateChangeSuccess',...) event to reload the localized enums if the language has been changed.
Let me know if this was not clear enough and/or you need a code example.

Related

DevExpress LookUpEdit Column Binding To Navigation Property

Good day!
I'm having an issue with the DevExpress LookUpEdit I can't figure out what the problem is.
I'm use Entity Framework list as a datasource.
public partial class provider_scheme : BaseEntity
{
public provider_scheme()
{
}
public int Provider_Scheme_RowID { get; set; }
public int Currency_RowID { get; set; }
public string Provider_Scheme_Name { get; set; }
public virtual currency currency { get; set; }
}
public partial class currency : BaseEntity
{
public currency()
{
provider_scheme = new HashSet<provider_scheme>();
}
public int Currency_RowID { get; set; }
public string Currency_ISOCode { get; set; }
public virtual ICollection<provider_scheme> provider_scheme { get; set; }
}
I'm setting the Datasource property of the LookUpEdit to IEnumerable<provider_scheme>, and setting up two column field names in my LookUpEdit. One for 'Provider_Scheme_Name' and one for 'currency.Currency_ISOCode'. But for some reason only the 'Provider_Scheme_Name' column values are showing. I've also checked and the 'currency' navigation property is being loaded.
Thanks in advance for your help
A bit late for an answer, but you might consider using the GridLookupEdit control instead. It permits adding all the columns you want

How Filter ng-options base on property in array property of object

I'm Using ng-options for fill my comb-box.I want to filter comb-box base on property of option which is array of class, I want to show option that the property contain the value I want.
I have Two comb-box, One of them List of hotel, other is list of the user which has list of Hotel they have access. I want when option in Hotel comb-box change the user com-box option show users that in listofhotelsaccses has hotel that its Id is equal with selected Hotel or isadmin property is true.
in C# I can use
' lstUserVm.Where(q => q.LstAccessHotelVms.Any(x => x.HotelID == hotelid) || q.IsAdmin == true).ToList();'
in angular I am amateur. I don't know how to filter the list.
class AccessHotel
{
public int HotelID { get; set; }
public string HotelName { get; set; }
public bool AccessFlag { get; set; }
}
class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string FullName { get; set; }
public bool IsAdmin { get; set; }
public List<AccessHotelVm> LstAccessHotelVms { get; set; }
}
class Hotel
{
public int HotelID { get; set; }
public string HotelName { get; set; }
}
<select class="form-control " id="mHotel" name="mHotel" ng-model="mHotel" data-ng-options="Hotel.HotelID as Hotel.Name for Hotel in LstHotel"
></select>
<select class="form-control " id="mUser" name="mUser" ng-model="mUser" data-ng-options="user.Id as user.FullName for user in LstUser " ></select>
I want To Change in hotel result in option in User but I Don't know how to filter it In angular.
I used something like this for Country and State filtering in my Project.
<select ng-model="userState" ng-options="state.name for state in ( states | filter: {country: { code: userCountry.code }}) track by state.name">
Try this Fiddle:
It'll help.
Click to view Fiddle.
You can use ng-change directive on your first select to call a function when user selects a value.
<select class="form-control" ng-change="filterUsers()" id="mHotel" name="mHotel" ng-model="mHotel" data-ng-options="Hotel.HotelID as Hotel.Name for Hotel in LstHotel"></select>
inside your filterUsers function you can filter LstUser according to the value selected.
$scope.mHotel contains the selected value from your first select
$scope.LstUser is the list that your select is populated with
You can update LstUser according to the selected value to only show the relevant items.
$scope.filterUser = function(){
// write your filter logic here
}

Many-to-many relationship read and write

I just want to get some clarity about link table for a many-to-many relationship in a ASP.NET MVC project. When the Controller and the Views are created, it seems like there are not any code for read and write to the link table!? The only thing that is autogenrated is the table OrderEmployee.
If I have understood it right, for each order I create, I also need to add the ID of the Employee who handled it in the OrderEmployee table? And when I want to list the Oders and want to know each Employee who handled that Order, I need to read from the OrderEmployee table? I can't find any tutorials about how to read and write to and from a link table.
Do I have to add this read and write code on my own in the controller? Preciate if I can get some clarity about this!
public class Order
{
public int ID { get; set; }
public string Name { get; set; }
public int? ManufacturerID { get; set; }
public virtual Manufacturer Manufacturer { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public int EmployeeNumber { get; set; }
public virtual ICollection<Timeunit> Timeunits { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
For reading and writing in a many to many relationship is not really difficult but hard to get it right in the beginning.
You don't have to add anything in your models, they are right.
Writing
I'll show you with an example of how to add a single order to an employee with a dropdown list. The concept for add multiple orders to employees is nearly the same, you'll find a link at the bottom with a tutorial.
First of all you should create view models like this :
public class CreateEmployeeViewModel
{
public int ID { get; set; }
public string Name { get; set; }
public int EmployeeNumber { get; set; }
public int SelectedOrderID { get; set; }
public SelectList OrdersList { get; set; }
}
Then in your EmployeesControler :
// GET: Employees/Create
public ActionResult Create()
{
/* Add this */
CreateEmployeeViewModel model = new CreateEmployeeViewModel();
model.OrdersList = new SelectList(db.Orders.ToList(), "ID", "Name");
return View(model);
}
The first parameter will be the list of objects in which you want to select something (an Order in this case). The second parameter is the name of the propertie of your Order you want to pass to the view model (as SelectOrderID) and finally the third parameter is the value you want to display in the dropdownlist.
And in your Create.cshtml replace the first line with this :
#model TestStackOverflow.Models.CreateEmployeeViewModel
Next add the dropdown list in the Html.BeginForm :
<div class="form-group">
#Html.LabelFor(model => model.OrdersList, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SelectedOrderID, Model.OrdersList, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SelectedOrderID, "", new { #class = "text-danger" })
</div>
</div>
Now you should have this in the create view.
Then go back to your EmployeesControler and find the POST method for create and replace it with this :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CreateEmployeeViewModel model)
{
if (ModelState.IsValid)
{
Employee employee = new Employee()
{
Name = model.Name,
ID = model.ID,
EmployeeNumber = model.EmployeeNumber,
Orders = new List<Order>()
};
employee.Orders.Add(db.Orders.Where(x => x.ID == model.SelectedOrderID).FirstOrDefault());
db.Employees.Add(employee);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
It will create a new Employee based on the view model values and add an order to this Employee. Now if you check your OrderEmployees table you should see that a new entry is created when you're adding an Employee.
Reading
Reading the values is really simpler than writing.
If you want to read all the employees that are handling an order, just do it like this (I took Index.cshtml from the Orders to demonstrate it)
Add this at the top of your file:
#using YourNameSpace.Models
And now a little further modify the file. It should look like this:
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.ManufacturerID)
</td>
<td>
#foreach (Employee e in item.Employees)
{
#e.Name <br />
}
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
Here you can find a tutorial on how to use SelectList to handle one to many relationships and many to many relationships in your views.
Hope this answer will help you.

How to grab a property object from DB

I'm having some doubts, maybe newbie doubts but I just got into ASP.NET MVC 4
Basically I would like to know the correct way of grabbing details of an Object inside a model.
In this case Image inside Contractor.
Model:
public class Contractor {
[Key]
public int ContractorID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Address { get; set; }
public Image Avatar { get; set; }
}
public class Image {
[Key]
public int ImageID { get; set; }
[Required]
public string File_name { get; set; }
[Required]
public byte[] File_data { get; set; }
}
public class DATACRUD : DbContext {
public DbSet<Contractor> Companies { get; set; }
public DbSet<Image> Images { get; set; }
}
Controller:
private DATACRUD db = new DATACRUD();
public ActionResult GetContractorAvatar(int id)
{
Contractor contractor = db.Contractors.Find(id);
if (contractor == null)
{
return HttpNotFound();
}
Image avatar = contractor.Avatar;
Problem 1)
avatar == null, but is not suppose to be because when I created the object Contractor, I added the image sucessfully (I checked in the DB and it is there)
The solution I'm seeing is instead of having Image property in Contractor.cs model, I would just put a string property with the image key.
Problem 2)
Even If could grab the image key like I said in the previous problem, when I pass my mouse in Debug mode over
private DATACRUD db = new DATACRUD ();
db.Images is also empty...
return File(avatar.File_data, "image");
}
Because you haven't defined your Image navigation property as virtual, you will have to eager load the Image when loading a Contractor:
db.Contractors.Include("Avatar").SingleOrDefault(c => c.ContractorID == id);
OR
// using System.Data.Entity;
db.Contractors.Include(c => c.Avatar).SingleOrDefault(c => c.ContractorID == id);

How to pass arrays from model to view?

I'm just learning ASP.NET MVC 3, And recently I tried a lot of times to pass arrays/lists/ICollections etc. but couldn't. everytime the list was empty.
For example, the current project:
Model:
public class Video
{
public int VideoID { get; set; }
public string Name { get; set; }
public ICollection<string> Tags { get; set; }
}
Initializer - Seed:
protected override void Seed(DatabaseContext context)
{
var videos = new List<Video>
{
new Video {
Name = "Video01",
Tags = new List<string> { "tag1", "tag2" },
};
videos.ForEach(s => context.Videos.Add(s));
context.SaveChanges();
base.Seed(context);
}
In the view: I do get the Name property, but the Tags are completely empty.
In the debug I get Tags - Count: 0.
This is not the first time it happens to me, to be honest it happens every single time when I try to pass those kind of stuff. a bit of info about the project:
ASP.NET MVC 3, Entity-Framework:Code First, SqlServerCe.4.0.
Crean an entity Tag
public class Video
{
public int VideoID { get; set; }
public string Name { get; set; }
public ICollection<Tag> Tags { get; set; }
}
public class Tag
{
public int TagId { get; set; }
public int VideoId { get; set; }
public string TagText { get; set; }
}
or store tags to one field separated with comma /semicolon or whatever fits for your solution
By default Entity Framework doesn't load associations of an entity, you need to specify it explicitly:
var videos = context.Videos.Include("Tags");

Resources