views:

56

answers:

3

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?

+1  A: 

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
}
Adrian Godong
This feels like it goes against having lean actions that have a single responsibility.
R0MANARMY
A: 

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

Sparky
Because you can't overload a method using the same signature. From C#'s perspective, you're trying to define the same function twice.
Frank Schwieterman
Because it does not compile
Paco
A: 

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);
}
rick schott
So user does not come from DB in your case. SaveChanges will not work.Not sure why you use TryUpdateModel if you have user as action parameter.
Evgenyt

related questions