Question

I have the following action method:-

public ActionResult Index(string searchTerm=null)
        { 
var accountdefinition = repository.FindAccountDefinition(searchTerm).ToList();
return View(accountdefinition);
 }

And the following repository method:-

public IQueryable<AccountDefinition> FindAccountDefinition(string q)
        {
            return from ad in entities.AccountDefinitions.Include(a => a.SDOrganization)
                   where (q == null || ad.ORG_NAME.ToUpper().StartsWith(q.ToUpper()) )
                   select ad;}

And the following part of the view:-

foreach (var item in Model) {
    <tr>
@*        
        <td class="center">
            @Html.DisplayFor(modelItem => item.ORG_NAME)
        </td>

Currently the actual data retrieval will occur when the .tolist() method is called inside the Action method. But my question if there is an actual differences between retrieving the data from the Action method or leaving it till the view is executed (in this case i should remove the .tolist() method)

Was it helpful?

Solution

It is will work perfectly if you remove .ToList() in the Index action. When ever a loop is done over an IEnumerable, internally it will execute the query.

But there are few points needs to be considered,

  1. It is always better to handle the exception scenarios in code, rather than the view. If the query returns null or throws an Exception, it can be gracefully handled with in action.sometimes db connection exceptions might occur.
  2. Executing DB query is not advised to run from Views. In case of a normal list/query over some retrieved data is fine.
  3. Logging exceptions will be easier in action than in the views.

So, if you are sure the query always works with out exceptions, you can remove the ToList() from Action. But it is always advised to pass the data (not query) to Views.

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