Question

First post time,

I've been playing around with MVC abit... I have a view which has multiple input fields, some of these fields can be blank on post.

The action method inside the controller for the post looks something like this

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

I've been using the DynamicQuery extension which has been kicking around in order to perform dynamic Linq querys on my database and I've encapsulated this in a Search object which is passed to the data access layer for execusion.

However, I also have a customized ViewData object which is passed back to the view for displaying the input values and the results of the query.

It all looks a little nasty in code as I'm having to set both the Search object properties AND the ViewDatas.

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 over thinking this and really should just pass the values to the data access layer and populate the ViewData in the controller, or is there a much more elegant pattern or practise I could use?

Sorry if this seems dump, not allot of people to bounce ideas off and time to dig into the framework.

Was it helpful?

Solution

According to your snippet MemberViewData class has the Results property in addition to properties of Search class. So first step would be to make MemberViewData derive from Search and define a constructor that accepts Search instance as parameter and assigns it's basic properties from it. Next I would change the action method like so:

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

OTHER TIPS

Use modelbinder to bind data

Like Tadeusz mentioned, a ModelBinder can help build the MemberViewData for you, which would leave only the results to be fetched.

You could also decide on creating a presentation service that understands how to build this view data object and simply delegate to it. I'd prefer the model binder approach here though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top