我有一个Person DB表,其中包含姓氏,名称和IdCity字段。
在View中,我实现了一个自动填充字段,让用户为城市数字。
我应该如何设计用于处理idCity的ViewModel以及如何将其传递给控制器?它是一个字符串,但我需要传递id并最终插入数据库中,如果它还不存在于数据库中。任何人都可以帮助我吗?
答案 0 :(得分:1)
在您的查看操作中接收城市名称,然后查看是否存在此名称的城市。如果是,请使用其ID。如果它没有创建新的,并使用该ID:
public ActionResult Update(PersonModel model)
{
var city = _cityRepository.GetCityByName(model.CityName);
if (city == null) _cityRepository.Add(city);
// At this point city.Id contains your city Id
var person = new Person
{
...
CityId = city.Id,
...
};
// Proceed to save your Person object
}