使用Dictionary接收前端数据,并用反射更新对像数据
前端调用方式
wx.request({
url: app.globalData.serverHttpUrl + "/JoinTeam/UpdateLeader",
data: { TeamId: thisProxy.data.theTeam.TeamId, PlayerId: e.currentTarget.id },
method: 'PUT',
header: { 'Cookie': wx.getStorageSync('wxloginToken'),'content-type': 'application/x-www-form-urlencoded' },
success: (res) => {
console.log(res)
}
})
控制器
/// <summary>
/// 变更球队相关信息
/// </summary>
/// <param name="teamNewInfo"></param>
/// <param name="uploadFiles"></param>
/// <returns></returns>
[HttpPut("Update")]
public async Task<JsonResult> PutAsync([FromForm] Dictionary<string, string> DictKeyValue, [FromForm] IFormCollection uploadFiles)
{
return new JsonResult(await _DataTeamRep.UpdateRecInfo(DictKeyValue));
}
数据操作
/// <summary>
/// 更新记录信息
/// </summary>
/// <param name="RecNewInfo">新的球队信息</param>
/// <param name="tempLogos">新的球队Logo文件</param>
/// <returns></returns>
public async Task<VMResult<MTeam>> UpdateRecInfo(Dictionary<string, string> DictKeyValue)
{
if (DictKeyValue==null || !DictKeyValue.Keys.Contains("Id"))
{
return new VMResult<MTeam>() { ResultCode = -1, ResultMsg = "S:参数不正确",ResultEntity=null };
}
//查询需要修改的球队记录。
MTeam WillUpdateRec = await _DbContext.tb_team.FindAsync(DictKeyValue["Id"]);
if (WillUpdateRec == null)
{
return new VMResult<MTeam>() { ResultCode = -2, ResultMsg = "S:未找到球队", ResultEntity = null };
}
//更新需要更新的字段
List<string> NoUpdateFields = new() { "Id", "CreateTime" };
var RecNewInfoProperties = WillUpdateRec.GetType().GetProperties();
foreach (var item in RecNewInfoProperties.Where(x => !NoUpdateFields.Contains(x.Name)).ToList())
{
if(DictKeyValue.Keys.Contains( item.Name))
{
switch (item.PropertyType.Name)
{
case "Int32":
item.SetValue(WillUpdateRec, Int32.Parse(DictKeyValue[item.Name]));
break;
case "String":
item.SetValue(WillUpdateRec, DictKeyValue[item.Name]);
break;
}
}
}
if (await _DbContext.SaveChangesAsync() > 0)
{
return new VMResult<MTeam>() { ResultCode = -2, ResultMsg = "S:更新成功", ResultEntity = WillUpdateRec };
}
else
{
return new VMResult<MTeam>() { ResultCode = -3, ResultMsg = "S:未更新信息", ResultEntity = null };
}
}
}
}