ASP.NET MVC - Partially updating model from view

前端 未结 6 718
独厮守ぢ
独厮守ぢ 2021-01-31 20:17

I just wondered how people were approaching this situation. It\'s something that seems like a weak point in my usage of MVC with ORMs (NHibernate in this case)...

Say y

6条回答
  •  别那么骄傲
    2021-01-31 21:04

    I use a similar approach to yours (in my case Entity Framework) with Entity -> ViewModel -> View but only on views with "complex" entities that have either 1:M or M:M relationships. In most cases I took the low road and went for Entity->View when I have a simple entity.

    My ViewModel is defined as Entity+supporting properties: SelectList or MultiSelectList and either a string or List. I'll also use a ViewModel for instances where I have properties I need for the view but may not necessarily need in the entity (database).

    Http Get controller methods are straightforward ActionResults with return View(repository.FetchNewViewModel()) for Create or repository.FetchModelById(id) for Edit. In both instances I'm initializing my entities before passing them to the view.

    Create([Bind(Exclude = "Entity.EntityId")] ViewModel model) and Edit(ViewModel model) are the Http Post controller methods of Create and Edit. My Edit view has a hidden input field for EntityId to pass it back and forth.

    By the time the Http Post method has the viewmodel, I lose all Entity.Relation and ViewModel.(Multi)SelectList values. I have to rebuild the object if I want my view to display properly: `

    try
    {
        var tags = model.TagIds; // List or  depending on your Id type
        if (model.TagsList == null) // It will be
        {
            model.TagsList = _repository.FetchSelectedTags(tags); // Build a new SelectList
        }
    
        if (!ModelState.IsValid)
        {
            return View(model);
        }
    
        _repository.Add(model.Article, tags); // or Save() for Edit
    }
    catch
    {
        return View(model); // Generally means something screwed in the repository class
    }
    
    return RedirectToAction("Index");
    

    `

    There is maybe 30% of my entity base using a ViewModel so I definitely only use it as needed. If you have complex views and model data in most instances you can probably break it down to smaller views.

提交回复
热议问题