Adding and removing items dynamically in the same view with Entity Framework and MVC

I was on the same question in different forms now (see for example Entity Framework and MVC 3: relations cannot be changed since one or more foreign -keys are not null) and it still listens to me, so I thought that I will add it in a more general form:

I feel this may not be a very unusual problem:

You have an entity object (using the Entity Framework), say, User. The user has some simple properties such as FirstName, LastName, etc. But it also has some object property lists, for receiving simple emails to make it simple. E-mail is often created as a list of objects, so you can add properties such as "Address" and "Type" to these objects ("Home", "Work", etc.). I use this as an example to keep it universal, but it can be anything, the fact is that you want the user to be able to add an arbitrary number of these elements. You should also be able to delete items (old address or something else).

Now, on a regular web page, you expect that you can add these elements in the same way. But MVC seems to only simplify this if you call a completely new view just to add an address. (In the template for viewing indexes, you get the link "Create a new one", for example.).

I came across several examples that do something close to what I mean here:

http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

and

http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/

, , , ( ), , - - Entity Framework. , ... AutoMapper , Entity Framework .. (. ).

, , - , , ? , (, )? , , , ( , , , ).

, , ( ), , .

+3
1

, ? Sack , .

public class Sack
{
    public IEnumberable<Gift> Gifts { get; set; } 
}

, , , . , , HtmlHelper, Html.EditorFor(m => m.SomeProperty), - , .

public static class HtmlExtensions
{
    public static IHtmlString CollectionEditorFor<TModel, TValue>(this HtmlHelper html, Expression<Func<TModel, TValue>> expression)
    {
        if (/* type of expression value is not a collection */) throw new FailureToFollowTheRulesException("id10t");

        // your implementation
    }
}
0

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


All Articles