Erik T.
Erik T.

Reputation: 370

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!

Upvotes: 0

Views: 110

Answers (1)

Rahul
Rahul

Reputation: 77934

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

Upvotes: 2

Related Questions