ASPNET MVC: autocomplete field but need to save the ID
I have a Person DB table that has a surname
, name
, and IdCity
fields.
In the View, I've i开发者_开发问答mplemented an autocomplete field to let the user digit the city.
How should I design the ViewModel for handling the IdCity
and how can I pass it to the controller? It is a string but I need to pass the id and eventually insert it in the DB if it does not exist there yet.
Receive the city name in your view action, then look if a city exists for this name. If it does, use its ID. If it doesn't create a new one, and use that 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
}
精彩评论