When creating a new Item in a Sharepoint list, the redirection works according to these rules:
- If the URL contains a valid “Source” parameter, the user user will be redirected to this URL
- Otherwise the user will be redirected to the default view of the list, such as AllItems.aspx
There are different approaches to change this behavior:
Via URL Parameter
One appraoch is to override the redirection by changing the Source parameter of the URL. This means the incoming link to the NewForm.aspx contains the redirection URL already. This is pretty static, sometimes you want to set the redirection on the fly. Also the appraoch enforces the same redirection for both Safe and Close buttons on the form.
Via Event Receiver
It is possible to redirect within an event receiver. This means placing a redirect command within a synchrounous event which aborts the normal event flow in a way, that asynchrounous events and other attached event receivers won’t work anymore.
Via Custom Safe Buttons
It is possible to replace the default buttons on the NewForm.aspx page by custom controls. So basically you develop a custom button that inherits from the Sharepoint “SaveButton” class. In there you can apply custom logic for redirection.
Via JavaScript
This is a novel approach I developed to get more flexibility and stability for the redirection behavior. It allows to set the redirection on the clientside.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
$(document).ready( function () { var
button = $( "input[id$=SaveItem]" ); // change redirection behavior button.removeAttr( "onclick" ); button.click( function () { var
elementName = $( this ).attr( "name" ); var
aspForm = $( "form[name=aspnetForm]" ); var
oldPostbackUrl = aspForm.get(0).action; var
currentSourceValue = GetUrlKeyValue( "Source" ,
true , oldPostbackUrl); var
newPostbackUrl = oldPostbackUrl.replace(currentSourceValue,
"MyRedirectionDestination.aspx" ); if
(!PreSaveItem()) return
false ; WebForm_DoPostBackWithOptions( new
WebForm_PostBackOptions(elementName,
"" ,
true ,
"" , newPostbackUrl,
false ,
true )); }); }); |
So basically we modify the click behavior of the create button on the NewForm.aspx to pass in a new “Source” parameter value just before the form is submitted.