views:

1048

answers:

3

I am writing an account management controller and have to process deleting of own user's account separately:

[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(string userName, string confirmButton)
{
    MembershipService.DeleteUser(userName);

    if (User.Identity.Name.Equals(userName,
        StringComparison.InvariantCultureIgnoreCase))
    {
        FormsAuth.SignOut();

        return View("DeleteSelf");
    }
    else
        return RedirectToAction("Index");
}

But partial view LogOnUserControl.ascx still shows just logged out user name while displaying DeleteSelf view because Request.IsAuthenticated and Page.User.Identity values are still set after FormsAuth.SignOut().

Adding a new action ShowDeleteSelfMessage could solve the problem but I don't like this solution:

    ...
    {
        FormsAuth.SignOut();

        return RedirectToAction("ShowDeleteSelfMessage");
    }
    ...

public ActionResult ShowDeleteSelfMessage()
{
    return View("DeleteSelf");
}

Any other ideas? Thank you!

A: 

In Delete action, instead of return View("DeleteSelf"), try this return Redirect("DeleteSelf")

Buu Nguyen
I tried and learned what unfortunately this is equivalent to RedirectToAction("DeleteSelf")
Alexander Prokofyev
Isn't that different from your OP, which is return View("DeleteSelf")?
Buu Nguyen
Unfortunately the same. But I think now what adding separate action to show a view is common pattern.
Alexander Prokofyev
A: 

I have examined the source code of standard AccountController.cs file and found two methods

public ActionResult ChangePasswordSuccess()
{
    return View("ChangePasswordSuccess");
}

and

public ActionResult RestorePasswordSuccess()
{
    return View("RestorePasswordSuccess");
}

which only show corresponding views. So my

public ActionResult ShowDeleteSelfMessage()
{
    return View("DeleteSelf");
}

method will look good in such company. Though I should change the name for consistency.

Alexander Prokofyev
+1  A: 

Change your LogOnUserControl.ascx to deal with ViewData["UserDeleted"]:

[Authorize]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(string userName, string confirmButton)
{
    MembershipService.DeleteUser(userName);

    if (User.Identity.Name.Equals(userName,
        StringComparison.InvariantCultureIgnoreCase))
    {
        FormsAuth.SignOut();

        // ***
        ViewData["UserDeleted"] = true;
        // ***

        return View("DeleteSelf");
    }
    else
        return RedirectToAction("Index");
}

LogOnUserControl.ascx:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<% if (Request.IsAuthenticated && !(ViewData["UserDeleted"] ?? false)) { %>
    Welcome <b><%= Html.Encode(Page.User.Identity.Name) %></b>!
    [ <%= Html.ActionLink("Log Off", "LogOff", "Account") %> ]
<% } else { %> 
    [ <%= Html.ActionLink("Log On", "LogOn", "Account") %> ]
<% } %>
eu-ge-ne