My action controller code looks amateurish

First time,

I have been playing around with MVC abit ... I have a view that has multiple input fields, some of these fields may be empty in the post.

The action method inside the controller for the message looks something like this:

public ActionResult Filter(int? id, string firstName, string lastName, bool? isMember)

      

I used the DynamicQuery extension that ran to execute dynamic Linq queries on my database and I encapsulated this in a search object that is passed to the data access layer for execusion.

However, I also have a custom ViewData object that goes back to the view to display the input values ​​and query results.

Everything looks a little messy in the code as I need to set both the properties of the search object and the ViewDatas objects.

public ActionResult Filter(int? id, string firstName, string lastName, bool? isMember)  { 
var search = new Search { 
Id = id, 
FirstName = firstName, 
LastName = lastName, 
Member =  isMember 
}; 

var memberViewData = new MemberViewData { 
Id = id, 
FirstName = firstName, 
LastName = lastName, 
Member =  isMember
}; 

memberViewData.Results = _dataRepository.GetMember(search); 

return View("Search", memberViewData); 

}

      

Am I thinking about this and should I really just pass values ​​to the data access layer and populate the ViewData in the controller, or is there a much more elegant pattern or practice I could use?

Sorry if this sounds like a dump, don't highlight people to discard ideas and time to delve into the box.

0


a source to share


3 answers


According to your method, the MemberViewData class has a Results property in addition to the properties of the Search class. So the first step would be to make MemberViewData a search result and define a constructor that takes the search instance as a parameter and assigns base properties to it. Then I would change the action method like this:



public ActionResult Filter(Search search)  
{ 
    return View("Search", new MemberViewData(search) 
    {
        Results = _dataRepository.GetMember(search)
    }); 
}

      

+1


a source


Use data binding for data binding



+2


a source


As Tadeusz mentioned, ModelBinder can help you create a MemberViewData that only leaves the results to be fetched.

You might also decide to create a presentation service that understands how to construct this view data object and simply delegate to it. I would prefer the model to be stapled here.

0


a source







All Articles