Add SharePoint Context Parameters to your MVC Provider Hosted App Form POST


You’re developing a SharePoint provider hosted app and you need to do a form post to a controller action, and in that controller action you need to get a SharePoint context using the SharePointContextProvider class.

When you do this, you may find that an exception is thrown by this class because there aren’t any of the SPxxxx query-string parameters, SharePointContextProvider needs at least the SPHostUrl parameter to be present and if you don’t add this to your route parameters for GET/POST, then you’ll get this exception.

You can do this quite easily by adding SPHostUrl/SPAppWebUrl et al as ‘route parameters’ using a RouteValueDictionary to the Html.BeginForm(…) markup in your razor file…

mvc-post-sp-01

As seen above I create the SPxxx query-string parameters as additional route data by storing the values in the ViewBag in the controller action…

mvc-post-sp-02

and the code for this is simple enough…

[gist ca47133a6887599e72b0/]

 

Published by

Phil Harding

SharePoint Consultant, Developer, Father, Husband and Climber.

2 thoughts on “Add SharePoint Context Parameters to your MVC Provider Hosted App Form POST

  1. Just an FYI – this approach will never work for FormMethod.Get (e.g. sending forms with GET method), because according the HTML spec that is implemented by browsers, any query string param that exists in the URL of the form action will get wiped away and replaced by the form values.

    A better solution would be to create a new HTML Form helper that writes out the SP Context data into hidden input fields within the form element, so they can be passed in as form data regardless of which method is used by the form – POST or GET.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.