Best ASP.NET MVC practice for distinguishing between GET / POST action methods with the same signature?

When implementing the "Edit" action, I add two methods for Get and Post: Change (string identifier)

Ideally, they should have the same signature. But of course, this is not possible. Therefore, I am adding a dummy parameter to the 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 the edit action?

+3
source share
4 answers

, . "_POST" . [ActionName("actualname")], .

+7

:

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

    // POST logic
}
-1

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 corresponding HTTP request to be processed by the proper method.

-1
source

The message must have an identifier in the IMO model:

[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);
}
-1
source

Source: https://habr.com/ru/post/1752849/


All Articles