Search code examples
c#asp.net-mvccode-duplication

Bypass redundant code in controller


I have two methods in my controller that are called via ajax on click. Both do the exact same thing (retrieving the same data from a database) and return a partial view along with the model that contains the retrieved data. The only difference is the view.

public PartialViewResult FormA()
{
    [...// Code]

    return PartialView("_FormA", ModelWithData)
}

public PartialViewResult FormB()
{
    [...// same Code as in FormA()]

    return PartialView("_FormB", ModelWithData)
}

Both views use the same data but show different things.

If FormB() is called FormA() definitely has been called before.

There must be a way to bypass the second method/database request. It perceptibly slows down the application due to the additional database request.

My question seems really stupid to me, but I'm not able to find a workaround...

Thx for your help!


Solution

  • Yes sure by passing some kind of filter to your action method like below

    public PartialViewResult ShowForm(string filter)
    { 
      if(TempData["model"]  == null)
      {  
        [...// Code]
       TempData["model"] = ModelWithData; 
      }
       if(filter == "some_condition")
        return PartialView("_FormA", TempData["model"] as ModelWithData);
       else
         return PartialView("_FormB", TempData["model"] as ModelWithData);
    }
    

    Got your point now. You can use any type of state management mechanish. Say TempData