Angular:如何使用Web API的实体属性映射有角相对形式控件

时间:2018-07-12 05:54:48

标签: angular entity-framework angular6

我正在做一个有角项目,正在使用Web API进行数据库操作。

由于我的实体属性具有首字母大写,但当我使用角度服务请求数据时,它仅以小写字母提供数据。为了进行映射,我还在表单控件中使用了小写字母,并在表格中显示了数据。

但是当我使用小写字母将数据发布到API时,它没有映射实体,例如,实体属性是EmployeeId,但是我发布的是employeeId。

注意。在这里,我使用HttpContext.Request.Form.Keys从角度和贴图实体中以FormData的形式发布数据。

如何发布表单控件,以便可以使用实体属性进行映射?

实体:

 public partial class TblEmployee
        {
            public int EmployeeId { get; set; }
            public string Name { get; set; }
            public string City { get; set; }
            public string Department { get; set; }
            public string Gender { get; set; }           
        }   

组件:

//to show data in table
<tr *ngFor="let emp of this.empdata">
          <td>{{ emp.employeeId }}</td>
          <td>{{ emp.name }}</td>
          <td>{{ emp.gender }}</td>
          <td>{{ emp.department }}</td>
          <td>{{ emp.city }}</td>
    </tr> 

//creating form controls using reactive forms
this.employeeForm = this._fb.group({
          employeeId: 0,
          name: ['', [Validators.required,
          Validators.minLength(3)]],
          gender: ['', [Validators.required]],
          department: ['', [
            Validators.required       
          ]],            
          city: ['', [
            Validators.required
          ]]
});  

    <input class="form-control" type="text" formControlName="name">
     <select class="form-control" data-val="true" formControlName="gender">
              <option value="">-- Select Gender --</option>
              <option value="Male">Male</option>
              <option value="Female">Female</option>
            </select>
 <input class="form-control" type="text" formControlName="department">
<select class="form-control" data-val="true" formControlName="city">
          <option value="">--Select City--</option>
          <option *ngFor="let city of cityList" value={{city.cityId}}>
            {{city.cityName}}
          </option>
        </select>

API调用:

public int Create()
        {
            TblEmployee employee = new TblEmployee();

            Dictionary<String, Object> _formvalue = new Dictionary<String, Object>();
            var aaa = HttpContext.Request.Form;
            foreach (string key in HttpContext.Request.Form.Keys)
            {
                _formvalue.Add(key, HttpContext.Request.Form[key]);
            }    
            foreach (string key in HttpContext.Request.Form.Keys)
            {
                var propertyInfo = typeof(TblEmployee).GetProperty(key); // getting propertyInfo null here becoz posted values are in small letters.
            }
}

1 个答案:

答案 0 :(得分:1)

您必须在启动类中应用以下配置来更改camelCase (JSON属性默认为camelCased)

 services.AddMvc ()
        .AddJsonOptions(opt => opt.SerializerSettings.ContractResolver = new DefaultContractResolver ());

在获得对地图的响应后,在角度项目中应该应用

(<FormGroup>this.employeeForm).setValue(response, { onlySelf: true });