Rusi Nova
Rusi Nova

Reputation: 2655

Re-factoring Controller's Action in asp.net mvc3

I am writing this Action code (within same controller) more than 10 times for different Models. Is there any way i can reduce this code or how can i create a generic action.

    [HttpPost]
    public ActionResult SavePerson(Person p)
    {
        if (ModelState.IsValid)
        {
            //do something
            return Redirect("/Main");
        }
        else
        {
            return View();
        }
    }


    [HttpPost]
    public ActionResult SaveCategory(Category c)
    {
        if (ModelState.IsValid)
        {
            //do something
            return Redirect("/Main");
        }
        else
        {
            return View();
        }
    }

Upvotes: 2

Views: 226

Answers (3)

archil
archil

Reputation: 39501

The main point is that //do something part always differs from action to action. So let's try to reduce all code other than that. You could use base controller for it

public class BaseController : Controller
{
    [NonAction]
    protected virtual ActionResult HandlePost<T>(T model, Action<T> processValidModel)
    {
        if (ModelState.IsValid)
        {
            processValidModel(model);
            return RedirectToAction("Main");
        }
        else
        {
            return View(model);
        }
    }
}

And in derived controller

public class DerivedController : BaseController
{
    [HttpPost]
    public ActionResult Create(Person person)
    {
       return HandlePost(person, p => _repository.Save(p));
    }
}

Upvotes: 5

Chris
Chris

Reputation: 2481

return ModelState.IsValid ? Redirect("/Main"):View();

as a start point would be the only line you need.

Upvotes: 0

Pankaj Upadhyay
Pankaj Upadhyay

Reputation: 13584

For functions which are going to be called too often, create a static class and define all such functions in that.

for example like following

public static class MyAppStaticClass
{
    public static SavePerson(Person p)
    {
        ... // your body
    }
}

Then, you can refer it like MyAppStaticClass.SavePerson whenever you need it.

Upvotes: -2

Related Questions