Evgenyt
Evgenyt

Reputation: 10721

Best ASP.NET MVC practice to distinguish GET/POST action methods with same signature?

When implementing Edit action, I add two methods for Get and Post: Edit(string id)

Ideally, they need have same signature. But of course this is not compilable. So I add a dummy parameter to HttpPost method (form in my case):

[HttpGet]
public ActionResult Edit(string id)
{
    var user = Entities.Users.SingleOrDefault(s => s.UserID == id);
    return View(user);
}

[HttpPost]
public ActionResult Edit(string id, FormCollection form)
{
    var user = Entities.Users.SingleOrDefault(s => s.UserID == id);
    if (TryUpdateModel<User>(user, new[] { "Email", "FullName" }))
    {
        Entities.SaveChanges();
        RedirectToAction("Index");
    }
    return View(user);
}

Any better/cleaner way to implement Edit action?

Upvotes: 3

Views: 2460

Answers (4)

Chris W
Chris W

Reputation: 3314

Give the methods a unique name in the controller e.g. add "_POST" as a suffix. You can then use the [ActionName("actualname")] attribute to mark you method with the name your action use.

Upvotes: 7

Sparky
Sparky

Reputation: 15075

Why not

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(string id,FormCollection form)  

and

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Edit(string id)  

This will cause the appropriate HTTP request to be handled by the proper method

Upvotes: -1

rick schott
rick schott

Reputation: 21117

The Post should have the id in a Model IMO:

[HttpGet]
public ActionResult Edit(string id)
{
    var user = Entities.Users.SingleOrDefault(s => s.UserID == id);
    return View(user);
}

[HttpPost]
public ActionResult Edit(User user)
{        
    if (TryUpdateModel<User>(user, new[] { "Email", "FullName" }))
    {
        Entities.SaveChanges();
        RedirectToAction("Index");
    }
    return View(user);
}

Upvotes: -1

Adrian Godong
Adrian Godong

Reputation: 8911

I would combine them into one:

public ActionResult Edit(string id)
{
    if (Request.HttpMethod == "GET") {
        var user = Entities.Users.SingleOrDefault(s => s.UserID == id);
        return View(user);
    }

    // POST logic
}

Upvotes: -1

Related Questions