开发者

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开发者_JS百科: 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?


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.


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
}


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);
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜