当更新狗的名字时,您需要将包括 DogId 在内的整个狗模型传回控制器。这样您就可以在数据库中查询狗记录并进行相应更新。以下示例使用实体框架
public class Dog
{
public int DogId { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
}
[HttpPost]
public async Task<ActionResult> UpdateDog(Dog model)
{
if(!ModelState.IsValid)
return View(model);
var dbDog = await db.Dogs.SingleAsync(x => x.DogId = model.DogId);
// ! at the beginning is shorthand for if the condition is false
// this is just a shorter way of doing the other example below
if(!string.IsNullOrEmpty(model.Name))
{
dbDog.Name = model.Name;
}
if(string.IsNullOrEmpty(model.Owner))
{
// model.Owner is null or an empty string so we don't want to
// update. We can leave this blank
}
else
{
// model.Owner has a value in it so we will update
dbDog.Owner = model.Owner
}
// you can update more properties here if you wish, or ignore them
// dbDog.Owner = model.Owner
await _db.SaveChangesAsync();
return View(model);
}
如果您不想将整个模型传回,您可以像现在一样传递您的 model.Name,但您还希望包含 model.DogId 以便您知道要更新数据库中的哪条记录.
UpdateDog?name=Max&dogId=4
希望这会有所帮助。
// 基于注释的AutoMapper实现
您需要创建一个映射配置文件,例如:
using AutoMapper;
public class DogProfile : Profile
{
public DogProfile()
{
CreateMap<DogViewModel, Dog>()
.ForMember(destination => destination.Owner, options => options.Condition(source => string.IsNullOrEmpty(source.Owner))
.ForMember(destination => destination.Name, options => options.Condition(source => string.IsNullOrEmpty(source.Name));
}
}
然后在你的 UpdateDog ActionResult 中你可以尝试:
使用自动映射器;
public class DogsController : Controller
{
private readonly IMapper _mapper;
public DogsController(IMapper _mapper)
{
_mapper = mapper
}
[HttpPost]
public async Task<ActionResult> UpdateDog(DogViewModel viewModel)
{
if(!ModelState.IsValid)
return View(viewModel);
var dbDog = await db.Dogs.SingleAsync(x => x.DogId = viewModel.DogId);
dbDog = _mapper.Map<Dog>(viewModel)
await _db.SaveChangesAsync();
return View(model);
}
}
另外,不确定您如何使用 AutoMapper,但如果您有,您可能需要在 Startup.cs 文件中的下面的 sn-p 中包含该行:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// Add this line
services.AddAutoMapper(typeof(Startup).Assembly);
}
}