0

I've got this issue in ASP.NET MVC model binding. I have an address object with a country child object. However - I'm using auto-complete for the country name. So in my view I've got something like this:

@Html.EditorFor(model => model.Country)

And I wrote a custom binder here:

    public class CountryBinder : IModelBinder
{
    public CountryBinder(DataContext db)
    {
        this.Db = db;
    }

    protected DataContext Db { get; set; }

    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var countryName = controllerContext.HttpContext.Request[bindingContext.ModelName];
        var result = Db.Countries.SingleOrDefault(
            country => country.EnglishShortName.Equals(countryName) | country.Translation_NL.Equals(countryName));
        return result;
    }
}

The data context is injected like this:

kernel.Bind<IDBContext>().To<DataContext>().InRequestScope();

Controller looks like this:

        var model = this.participationRepository.Single(p => p.Id == participation.Id);
        if (!participation.IsCancelled)
        {
            this.TryUpdateModel(model);

etc...

Every time I save - a new Country is created, with the exact specs of the country that we found in the binder, but with new id. Any clues?

tereško
  • 58,060
  • 25
  • 98
  • 150
Jochen van Wylick
  • 5,303
  • 4
  • 42
  • 64
  • Could you show code that is saving? – Kirill Bestemyanov Oct 27 '12 at 09:28
  • Hi Kirill, it's just Db.SaveChanges() – Jochen van Wylick Oct 27 '12 at 09:58
  • Thanks cap. Show please what is in your controller after modelbinding. How do you work with entities. What is a relation between participation and country and how do you initialize navigation property if it is. – Kirill Bestemyanov Oct 27 '12 at 10:02
  • Hi Kirill, The relation is Participation > Person > Addresss > Country. When investigating 'participation' instance that comes into the controller, the binding seems correct - That is, if I look at the Participatin > Person > Address > Country - it is the country with correct key and values from the DB, just like I would have wanted. If someone cancels his participation - I don't bother updating the model ( because in the UI, I hide all the fields ). But then I just call Db.SaveChanges() It's like I have to 'attach' the entities first, but they're from the same datacontext – Jochen van Wylick Oct 27 '12 at 10:14
  • Instead of creating the model binder for the country try creating model binder for the entity that you are going to save – VJAI Oct 27 '12 at 10:35
  • Well, that will be quite a lot of work. Do you propose that as a workaround, or is it better practice? – Jochen van Wylick Oct 27 '12 at 12:34

0 Answers0