views:

330

answers:

2

I am using the Ajax.BeginForm to create a form the will do an ajax postback to a certain controller action and then the response view is inserted into the UpdateTargetId.

using (Ajax.BeginForm("Save", null,
        new { userId = Model.UserId },
        new AjaxOptions { UpdateTargetId = "UserForm" },
        new { name = "SaveForm", id = "SaveForm" }))
   {
    [HTML SAVE BUTTON]
   }

Everything works great except when the Users session has timed out and then they are redirected back to the login page. The login page then gets returned from the Ajax call because of the Authorize attribute and the html gets loaded into the UpdateTargetId and therefore I end up with the login page html within the user profile page (at the Target Id). My controller action looks like this:

[Authorize]
public ActionResult Save(Int32 UserId)
{
    //code to save user
    return View("UserInfoControl", m);

}

How can I solve this problem?

A: 

See this question here:

http://stackoverflow.com/questions/743252/how-may-i-best-use-the-authorize-attribute-with-ajax-and-partial-views

Nissan Fan
Thanks for the link, but I am not using jQuery... just the ASP.NET MVC built-in Ajax.BeginForm helper (is this using jQuery?).
Jeff Widmer
Does the view that contains the partial have an Authorize attribute?
Nissan Fan
Not the View, but the Controller Action has the Authorize attribute. You can put an Authorize Attribute on the partial view?
Jeff Widmer
Sorry wrong terminology :)
Nissan Fan
A: 

I think that you can handle the authorization issue from inside the action. First remove [Authorize], the use this code:

public ActionResult Save(Int32 UserId)
{
    if (!User.Identity.IsAuthenticated) 
    { 
        throw new Exception();
    }
    //code to save user
    return View("UserInfoControl", m);

}

Then you can put a OnFailure condition in your AjaxOptions and redirect your page or something.

Francisco
I suppose that might work but then I am using an exception for business logic... which you never want to do.
Jeff Widmer