开发者

ASPNET MVC: autocomplete field but need to save the ID

开发者 https://www.devze.com 2023-03-30 16:08 出处:网络
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.

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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号