MVC.NET Domain Design Forms

The pattern I see in most .NET MVC examples is for your model to be an object passed between the controller and lower layers, and directly attached to them. I chose the domain-driven method , where I have domain objects running between layers. The idea was that these objects would be passed to the views.

The problem I am facing is with form pages. I was going to have separate objects for binding forms on the way back (which also contain validation annotations). I saved this separately from the domain object, because one object could be updated with different pages, and each page had its own verification requirements (for example, the address of a person may not even be displayed on one page, but require another, so validation will not always be work on a universal domain object). This complicates the situation when you return the form and must display errors.

Take, for example, the refresh page. I would print a view for my Person Person object, and the page would have the field values ​​populated with it. The postback action will take the form object for this page and confirm it. If it passed, I use automapperto copy the values ​​to the domain object from the form and save. It all works. Where it breaks down, this page is redisplayed in the presence of errors. If he typed a domain object, I would simply fill in the fields based on the old values ​​instead of the values ​​entered by the user. If it was entered into a form object, I need to translate all the objects of my domain to these form objects for each page (and may have to go through the domain object if I need some values ​​that I would use to read only for this page) .

I'm sure I don't notice / complicate anything here at all.

Update An interesting find after the game due to what @Charlino said. If I used strongly typed html helpers to input inputs (Html.TextBoxFor ()), it will remember the values ​​even if the view is typed onto a domain object. If I use generic (Html.TextBox ()) or raw HTML, this is not like.

+3
source share
1 answer

Having a ViewModel for each view is what I do.

This is a bit more relevant work, since I have to define the ViewModel and the display, but this code is so simple and simple that it only takes a few seconds to write.

, , Form ViewModel.

public class MyViewModel 
{
    public string SomeNonFormDisplayValue { get; set; }
    public bool AnotherDisplayOnlyValue { get; set; }
    public IEnumerable<Tuple<int, string>> SelectionListItems { get; set; }

    public MyViewsForm Form { get; set; }
}


public class MyViewsForm
{
    public string EditableProperty { get; set; }
    public int SelectionListItemId { get; set; }
}

View ViewModel, Post Action, .

public class MyController
{
    [HttpGet]
    public ActionResult Edit() { ... }

    [HttpPost]
    public ActionResult Edit(MyViewsForm form) { ... }
}

ViewModel, , - , POST'd .

+3

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


All Articles