How to handle nested models in ASP.NET MVC

I was looking for a good working solution on how to properly handle model binding with nested attributes. I have one model that has a list of other child models, as shown below:

public class Organization : IEntity { [ScaffoldColumn(false)] public int ID { get; set; } [LocalizedDisplayName("Goals")] public virtual ICollection<OrganizationGoal> Goals { get; set; } } 

In the controller, I am trying to update the data as follows:

 [HttpPost] public ActionResult Edit(string organizationIdentifier, FormCollection values) { var organization = organizationService.GetByIdentifier(organizationIdentifier); if (TryUpdateModel(organization)) { organizationService.Save(organization); return RedirectToAction("Edit"); } return View("Edit"); } 

But TryUpdateModel always returns false, and no validation messages are displayed in the user interface. The user interface is built using the standard MVC helper editor.

What is the best practice? For a fairly normal scenario, it is not so easy to find information.

Thanks!

+4
source share
1 answer

Now the identifier column you are requesting with GetByIdentifier? If so, why are you passing the string, but does it have an int value in the definition?

Also, after reading about TryUpdateModel, it looks like you might want to use UpdateModel instead.

http://msdn.microsoft.com/en-us/library/dd460189.aspx

0
source

Source: https://habr.com/ru/post/1314054/


All Articles