Polulate dynamic control in angularjs - angularjs

I've been developing a sample Single Page Web application using AngularJS + Asp.net Web API. I've been stuck at one point where I am not able to help my self, I've tried googling without any success.
My scenario is as following.
I've two entity 1)Car & 2)Dealer. I've one link table Car_Dealer. As per my sample scenario a specific car can be sold at multiple dealer. So my models at server side looks like below.
Car Model
namespace HelloWebAPI.Models
{
using System;
using System.Collections.Generic;
public partial class Car
{
public Car()
{
this.Car_Dealer = new HashSet<Car_Dealer>();
}
public int CarId { get; set; }
public string CarName { get; set; }
public string CarDetails { get; set; }
public virtual ICollection<Car_Dealer> Car_Dealer { get; set; }
}
}
Dealer Model
namespace HelloWebAPI.Models
{
using System;
using System.Collections.Generic;
public partial class Dealer
{
public Dealer()
{
this.Car_Dealer = new HashSet<Car_Dealer>();
}
public int DealerId { get; set; }
public string DealerName { get; set; }
public string DealerLocation { get; set; }
public virtual ICollection<Car_Dealer> Car_Dealer { get; set; }
}
}
Car Dealer Model
namespace HelloWebAPI.Models
{
using System;
using System.Collections.Generic;
public partial class Car_Dealer
{
public int Car_DealerId { get; set; }
public int CarId { get; set; }
public int DealerId { get; set; }
public virtual Car Car { get; set; }
public virtual Dealer Dealer { get; set; }
}
}
My server side controllers POST method is as below.
CarController.CS
public void Post(Car NewCar)
{
//to save the car data in the database.
Car NewCarObj = new Car();
NewCarObj.CarName = NewCar.CarName;
NewCarObj.CarDetails = NewCar.CarDetails;
objEntities.Cars.Add(NewCarObj);
foreach (Car_Dealer dealer in NewCar.Car_Dealer)
{
dealer.CarId = NewCarObj.CarId;
dealer.DealerId = NewCarObj.DealerId;
objEntities.Car_Dealers.Add(dealer);
objEntities.SaveChanges();
}
}
Code in App.js file is as below.
App.JS
var CreateCarCtrl = function ($scope, $location, Car, Dealer) {
$scope.items = Dealer.query({ q: $scope.query });
$scope.save = function () {
Car.save($scope.item);
$location.path('/CarListingScreen');
};
};
And this one is chunk of code from my template file that is AddCar.HTML
AddCar.HTML
<tr>
<td>
<label class="control-label" for="DealerName">Add Dealer</label>
</td>
<td>
<ul>
<li>
<select ng-model="item.DealerName">
<option ng-repeat="item in items">{{item.DealerName}}</option>
</select>
[<a href ng-click="items.splice($index, 1)">Remove</a>]
</li>
<li>[<a href ng-click="items.push({})">Add More</a>]
</li>
</ul>
</td>
</tr>
As we can see in Template file, I am trying to render the list of dealer in Drop Down list by two way binding as I am using the same template for Editing purpose also.
Hopefully you've got the scenario.
Now following are the questions for which I am looking for solutions
I should replace {{item.DealerName}} with something else so I can get that data back at server. What should be replaced ?
Neither Remove Nor Add More functionality is working. How can I make it functioning ?
How can I load data while editing the record ? I mean getting dealers filled in Dropdown & Creating number of dropdown accordingly to handle dealer ?
Please note here I can add more than one dealer so it should be handled in template also.
Edit
My form looks like below.
As we can see in screen shot user can add multiple dealers for specific car & Can remove added item also.
How to bind dropdown list of dealer as it's <Collection> of car dealer ?
How can I render Dropdown list dynamically while clicking Add More button & Getting this values back at server side?
Thanks a lot in advance.

There are still essential parts missing form your code so, i cannot answer all questions. But let me take a try
I should replace {{item.DealerName}} with something else so I can get
that data back at server. What should be replaced ?
The ng-model for this should be item.DealerId. When you post the complete car model it does not need to have the complete dealer object, just the Id should be enough. On the server you should get the dealer data based on your association before saving the car.
Neither Remove Nor Add More functionality is working. How can I make it functioning ?
I can tell remove is not working because the remove button is outside the ng-repeat and $index is not available outside, assuming you are trying Dealer to be removed by placing the remove button against each dealer. Try
<select ng-model="item.DealerName">
<option ng-repeat="item in items">{{item.DealerName}}</option>
[<a href ng-click="items.splice($index, 1)">Remove</a>]
</select>
For third point
How can I load data while editing the record ? I mean getting dealers
filled in Dropdown & Creating number of dropdown accordingly to handle
dealer ?
There should be a model on client side for list of dealers, which you can predefine or get it from server.
If the car has multiple dealers like Car.dealers, do a ng-repeat to render them
<div ng-repeat='dealer in Car.dealers'>
<select ng-model='dealer.id'ng-options='d.name for d in allDealers'>
</div>

Related

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
}

Displaying Specific Fields from Facebook Graph API JSON

I'm trying to simply display the list of members in a specific group using the Facebook Graph API. I'm using Newtonsoft.JSON.
Here is the results of my url query:
Graph API Results
I used a JSON class generator and it gave me this:
public class Datum
{
public string name { get; set; }
public string id { get; set; }
public bool administrator { get; set; }
}
public class Cursors
{
public string before { get; set; }
public string after { get; set; }
}
public class Paging
{
public Cursors cursors { get; set; }
}
public class Members
{
public List<Datum> data { get; set; }
public Paging paging { get; set; }
}
public class RootObject
{
public Members members { get; set; }
public string id { get; set; }
}
I've tried every combination I can think of to display simply the list of members in a multi-line text box, but not sure if this is even the best way to display the list on a Windows Form App.
Could someone help me understand 2 things.
1) What is the best component to display the list of names in a Windows Form App?
2) What is the 1 or 2 lines to generate just the list of names using JsonConvert.DeserializeObject from this?
My raw data is stored in: string responseFromServer = reader.ReadToEnd();
To deserialize the JSON into your classes:
RootObject obj = JsonConvert.DeserializeObject<RootObject>(responseFromServer);
To get the member names into a List<string>:
List<string> members = obj.members.data.Select(d => d.name).ToList();
Note: You need to have using System.Linq; at the top of your file in order to use the Select and ToList methods.
As far as displaying the data in a windows form app, there's not a "best" component-- it depends on what you're trying to accomplish as to what control you would choose to use. For example, if all you want to do is display the list of names in a multi-line textbox, you could do this:
textBox1.Text = string.Join("\r\n", members);
If you want to allow the user to be able to select individual names and do something based on that selection, you would probably want to use a ListBox or a ComboBox instead. You can populate a ListBox or ComboBox like this:
listBox1.DisplayMember = "name";
listBox1.DataSource = obj.members.data;
That should be enough to get you started.

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.

ng-init for select tag in angularJs

I tried to make a dropdown from a list of objects civility. But I dont know how to select the first item with an complexe object. I already do it with simple object and I don't understand why it doesn't work with my new dropdown list.
This is my select tag :
<select class="input-xlarg" id="listCivilities" ng-options="civility.Label for civility in civilities track by civility.CivilityID" ng-model="customer.Civility" ng-init="customer.Civility" required=""></select>
My list is loaded with an return of a controller asp.net MVC.
This is my model:
public int CivilityID { get; set; }
public string Label { get; set; }
public string Abbreviation { get; set; }
public int Order { get; set; }
public int CompanyID { get; set; }
So, like I said, my dropdown list load and display fine but I don't succeed to select the item who interest me.
If someone can help me to understand why it doesn't work.
Thanks.
Use ng-model as customer.CivilityID to bind CivilityID on selection.
and
civility.Label for civility.CivilityID in civilities in ng-options
Use this Selected Tag :
<select class="input-xlarg" id="listCivilities" ng-model="customer.CivilityID" ng-options="civility.Label for civility.CivilityID in civilities track by civility.CivilityID" required=""></select>
in Controller :
$scope.customer = {CivilityID : 1};
Updates : here is working Plunker

Binding List to HTML

does anyone know how to bind a list item to html in Nancy?
Here's the code I have:
Get["/topics"] = parameters
=>
{
var model = new TopicsModel();
model.Load(); // it populates some rows of type TopicModel
return Negotiate.WithStatusCode(HttpStatusCode.OK)
.WithModel(model)
.WithView("topics");
};
My TopicsModel:
public class TopicsModel
{
public void Load() { Models = ...}
public List<TopicModel> Models { get; set; }
}
and the TopicModel:
public class TopicModel
{
public string TopicName { get; set; }
public string TopicImageUrl { get; set; }
}
I've tried the below in my HTML but none of them seem to be working.
<div class="row">
<h3>TopicName[0]</h3>
<h3>#Model.Models[0].TopicName</h3>
<h3>Models[0].TopicName</h3>
</div>
The results for these three are (in order):
TopicName[0]
System.Collections.Generic.List`1[...Models.TopicModel][0].TopicName
Models[0].TopicName
I have also tried other things but none have worked.
Any help would be greatly appreciated.
Many thanks,
Update: Apparently it's not possible. I ended up using the Razor engine which works for my use-case.
https://github.com/NancyFx/Nancy/wiki/The-Super-Simple-View-Engine#iterators
#ForEach.Models
<div class="row">
<h3>#Current.TopicName</h3>
</div>
#EndEach
Be aware that Simple Simple View Engine does not support nested loops (currently)

Resources