我正在学习 Angular 2 (4),我对 Angular 表单有一点问题。问题是当我在下拉列表中选择该项目时,我无法从数据库中检索项目的值。因此,在我的情况下,当我在下拉列表中选择“品牌”时,我无法检索“品牌”的值。
这是我的“品牌”模型:
public class Brand
{
[Required]
public int BrandId { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
public string Description { get; set; }
//Relation
public virtual ICollection<Car> Cars { get; set; }
public Brand()
{
Cars = new Collection<Car>();collection
}
}
这是我的控制器:
[HttpGet("/api/brands")]
public async Task<IEnumerable<BrandResource>> GetBrands()
{
var brands = await context.Brands.Include(m => m.Cars).ToListAsync();
return mapper.Map<List<Brand>, List<BrandResource>>(brands);
}
我的映射配置文件:
public MappingProfile()
{
CreateMap<Brand, BrandResource>();
CreateMap<CarType, CarTypeResource>();
CreateMap<Car, CarResource>();
}
我的品牌服务:
@Injectable()
export class VehicleService {
constructor(private http: Http ) { }
getBrands(){
return this.http.get('/api/brands')
.map(res => res.json());
}
}
我尝试记录所选品牌值的组件:
@Component({
selector: 'app-vehicle-form',
templateUrl: './vehicle-form.component.html',
styleUrls: ['./vehicle-form.component.css']
})
export class VehicleFormComponent implements OnInit {
constructor(
private vehicleService: VehicleService) { }
brands: any[];
cars: any[];
cartypes: any[];
vehicle: any = {};
ngOnInit() {
this.vehicleService.getBrands().subscribe(brands =>
this.brands = brands
);
}
onBrandChange(){
var selectedBrand = this.brands.find(b => b.BrandId == this.vehicle.brand);
console.log(selectedBrand);
}
}
最后是我的表格:
<form>
<div class="form-group">
<label for="brand">Brand</label>
<select id="brand" class="form-control" (change)="onBrandChange()" [(ngModel)]="vehicle.brand" name="brand">
<option value=""></option>
<option *ngFor="let b of brands" value="{{ b.BrandId }}">{{ b.name }}</option>
</select>
</div>
</form>
那么我做错了什么?
编辑:我试图记录车辆:
onBrandChange(){
console.log("VEHICLE", this.vehicle);
}
这就是我得到的: 控制台
我想我应该得到这样的东西:Object{brand:"1"}。有谁知道可能是什么问题?