How to use pagination for displaying circles from Google+ - google-api

I have set maxResults to 10 and i want to know how to use view more circles with nextpageToken and by clicking View More button the next 10 circles have to display and goes on till the last circles in Google+. Please help me fix this issue.
Please see my code below :
<html>
<head>
<title>Google+ JavaScript Quickstart</title>
<script type="text/javascript">
(function() {
var po = document.createElement('script');
po.type = 'text/javascript'; po.async = true;
po.src = 'https://plus.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(po, s);
})();
</script>
<!-- JavaScript specific to this application that is not related to API
calls -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" ></script>
</head>
<body>
<div id="gConnect">
<button class="g-signin"
data-scope="https://www.googleapis.com/auth/plus.login"
data-requestvisibleactions="http://schemas.google.com/AddActivity"
data-clientId="my client id"
data-callback="onSignInCallback"
data-theme="dark"
data-cookiepolicy="single_host_origin">
</button>
</div>
<div id="authOps" style="display:none">
<h2>User is now signed in to the app using Google+</h2>
<p>If the user chooses to disconnect, the app must delete all stored
information retrieved from Google for the given user.</p>
<button id="disconnect" >Disconnect your Google account from this app</button>
<h2>User's profile information</h2>
<div id="profile"></div>
<h2>User's friends that are visible to this app</h2>
<div id="visiblePeople"></div>
<p>View More</p>
<h2>Authentication Logs</h2>
<pre id="authResult"></pre>
</div>
</body>
<script type="text/javascript">
var helper = (function() {
var BASE_API_PATH = 'plus/v1/';
return {
/**
* Hides the sign in button and starts the post-authorization operations.
*
* #param {Object} authResult An Object which contains the access token and
* other authentication information.
*/
onSignInCallback: function(authResult) {
gapi.client.load('plus','v1', function(){
$('#authResult').html('Auth Result:<br/>');
for (var field in authResult) {
$('#authResult').append(' ' + field + ': ' +
authResult[field] + '<br/>');
}
if (authResult['access_token']) {
$('#authOps').show('slow');
$('#gConnect').hide();
helper.profile();
helper.people();
} else if (authResult['error']) {
// There was an error, which means the user is not signed in.
// As an example, you can handle by writing to the console:
console.log('There was an error: ' + authResult['error']);
$('#authResult').append('Logged out');
$('#authOps').hide('slow');
$('#gConnect').show();
}
console.log('authResult', authResult);
});
},
/**
* Calls the OAuth2 endpoint to disconnect the app for the user.
*/
disconnect: function() {
// Revoke the access token.
$.ajax({
type: 'GET',
url: 'https://accounts.google.com/o/oauth2/revoke?token=' +
gapi.auth.getToken().access_token,
async: false,
contentType: 'application/json',
dataType: 'jsonp',
success: function(result) {
console.log('revoke response: ' + result);
$('#authOps').hide();
$('#profile').empty();
$('#visiblePeople').empty();
$('#authResult').empty();
$('#gConnect').show();
},
error: function(e) {
console.log(e);
}
});
},
/**
* Gets and renders the list of people visible to this app.
*/
people: function() {
var request = gapi.client.plus.people.list({
'userId': 'me',
'collection': 'visible',
'selfLink':'http://localhost/Google+/trail+.html',
'maxResults':10,`enter code here`
'items[]' : 'list',
'nextPageToken': 'CAIQ0K3cq5DEtAIgAygB'
});
request.execute(function(people) {
$('#visiblePeople').empty();
$('#visiblePeople').append('Number of people visible to this app: ' +
people.totalItems + '<br/>');
for (var personIndex in people.items) {
person = people.items[personIndex];
$('#visiblePeople').append('<img src="' + person.image.url + '">');
$('#visiblePeople').append(''+ person.displayName + '</br>'+ '</br>');
}
});
},
/**
* Gets and renders the currently signed in user's profile data.
*/
profile: function(){
var request = gapi.client.plus.people.get( {'userId' : 'me'} );
request.execute( function(profile) {
$('#profile').empty();
if (profile.error) {
$('#profile').append(profile.error);
return;
}
$('#profile').append(
$('<p><img src=\"' + profile.image.url + '\"></p>'));
$('#profile').append(
$('<p>Hello ' + profile.displayName + '!<br />Tagline: ' +profile.tagline + '!<br />Email id: ' +profile.email +
+ '<br />About: ' + profile.aboutMe + '</p>'));
if (profile.cover && profile.coverPhoto) {
$('#profile').append(
$('<p><img src=\"' + profile.cover.coverPhoto.url + '\"></p>'));
}
});
}
};
})();
/**
* jQuery initialization
*/
$(document).ready(function() {
$('#disconnect').click(helper.disconnect);
if ($('[data-clientid="YOUR_CLIENT_ID"]').length > 0) {
alert('This sample requires your OAuth credentials (client ID) ' +
'from the Google APIs console:\n' +
' https://code.google.com/apis/console/#:access\n\n' +
'Find and replace YOUR_CLIENT_ID with your client ID.'
);
}
});
/**
* Calls the helper method that handles the authentication flow.
*
* #param {Object} authResult An Object which contains the access token and
* other authentication information.
*/
function onSignInCallback(authResult) {
helper.onSignInCallback(authResult);
}
function getMore()
{
helper.people();
}
</script>
</html>

It looks like there may be a couple of issues here. You seem to have at least some of the gist of how to use people.list, but you seem to be trying to add some of the response fields to the request field. See https://developers.google.com/+/api/latest/people/list for full details of the request parameters and the expected response.
On the first call, you only need to pass the userId and collection parameters. Since you want to limit the page size, you'll need to pass maxResults as well, so your call will look something like
var requestParams = {
'userId': 'me',
'collection': 'visible',
'maxResults': 10
};
gapi.client.plus.people.list( requestParams ).execute(peopleCallback);
The parameter passed to peopleCallback() will contain the results, including a nextPageToken, which you will need to pass on subsequent calls to get additional items. You can store this token in a global variable, or as an attribute in your helper object, and process the other fields you need. So it might look something like this:
peopleCallback: function(response){
nextPageToken = response.nextPageToken;
items.forEach(function(item){
$('#visiblePeople').append(''+person.displayName+'');
});
}
The next time the "List more" button is called, you need to include the nextPageToken as part of your request, so the call would look something more like this:
var requestParams = {
'userId': 'me',
'collection': 'visible',
'maxResults': 10,
'pageToken': nextPageToken
};
gapi.client.plus.people.list( requestParams ).execute(peopleCallback);
Subsequent calls will get a new nextPageToken which should be passed the next time you're making a call to continue getting the list.
I leave it as an exercise to determine the best way for you to handle the differences between these calls (passing a token vs not), initializing the visiblePeople list, and other issues specific to your code structure.
One important caveat on what you're trying to do, however. Your question title suggests that you're trying to get circles of a person - this will not give you that info. The people.list call will give you people, not circles, that a person is willing to publicly say are added to a circle. A user may choose to not provide this information, or may choose to only provide a subset of the information, and you will not know what specifically named circles a person may have been added to

Related

How to render ajax response to view

Here is my predicament: I need to render json response received from controller method. I do this by calling clicking on navbar item "List Articles" which activate method ajaxIndex(). Then tat method makes request to route which in turn call controller method also called ajaxIndex(). That method then gater all articles and sends it as a response. After that, that response i can't control, it just renders raw json ...
Navbar item:
<a class="nav-link" href="/articles" onclick="ajaxIndex(this)"> List Articles </a>
Route:
Route::get('/articles', "ArticlesController#ajaxIndex");
Method in ArticlesController
public function ajaxIndex(Request $request)
{
$var1 = $request->var1;
$var2 = $request->var2;
$elem = $request->elem;
$currUser = auth()->user();
$currUri = Route::getFacadeRoot()->current()->uri();
$articles = Article::orderBy("created_at","desc")->paginate(5);
$html = view('articles.List Articles')->with(compact("articles", "var1", "var2", "elem", "currUser", "currUri"))->render();
//return $request;
return response()->json(["success"=> true, "html" => $html], 200);
//return response()->json(["success"=> $articles,"var1"=> $var1, "var2"=> $var2, "elem"=> $elem, "currUser" => $currUser, "currUri" => $currUri], 200);
}
and here my ajax method
function ajaxIndex(me,formId){
let var1 = "gg";
let var2 = "bruh";
let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let url = "/articles";
if(formId){
let form = $("#"+formId).serialize();
console.log(form);
}
$.ajax({
type: "GET",
url: url,
headers:{
"X-CSRF-TOKEN": token
},
data: {/*
var1: var1,
var2: var2,
elem: {
id: me.id ? me.id : null,
class: me.className ? me.className : null,
value: me.value ? me.value : null,
innerHTML: me.innerHTML ? me.innerHTML : null,
}
*/},
success: (data) => {
console.log(data);
$('#maine').html(JSON.parse(data.html));
},
error: (data) => {
console.log(data);
}
});
}
How to render acquired data to particular view?
Now just renders json response alongside html.
My question is how to render response itself and where goes response from controller method. I tried console logging it when route is hit, but there is nothing in console. What is actual approach or what i need to change to achieve this?
Addendum: "For List Articles you will send ajax request to rest api where it returns array of objects(articles)". I assumed i needed to make ajax request, after being sent to appropriate blade, i should now display sent data? Am i getting wrong something? ...
Edit1:
Now when i go to any page in my app, for example:
http://articleapp.test/articles?page=2
it shows json response:
Edit2:
I also modified my ajax method to correctly display current page for article listing. Problem start when try to go to next page.
Here is the code:
function ajaxIndex(me,formId){
let token = document.querySelector("meta[name='csrf-token']").getAttribute("content");
let url = "/articles";
if(formId){
let form = $("#"+formId).serialize();
console.log(form);
}
$.ajax({
type: "GET",
url: url,
headers:{
"X-CSRF-TOKEN": token
},
data: {},
success: (data) => {
console.log(data);
let html = "<div class='container'>";
let articleBody = "";
let pagination = "<ul class='pagination'><li class='page-item'><a class='page-link' href='#'>Previous</a></li>";
if(data.articles.data.length > 0){
for(let i=0;i<data.articles.current_page;i++){
let created_at = data.articles.data[i].created_at.replace(/-/g,"/").split(" ")[0];
html += "<div class='row' style='background-color: whitesmoke;'><div class='col-md-4 col-sm-4'><a href='/articles/"+data.articles.data[i].id+"'><img class='postCover postCoverIndex' src='/storage/images/"+data.articles.data[i].image+"'></a></div><div class='col-md-8 col-sm-8'><br>";
if(data.articles.data[i].body.length > 400){
articleBody = data.articles.data[i].body.substring(0, 400);
html += "<p>"+articleBody+"<a href='/articles/"+data.articles.data[i].id+"'>...Read more</a></p>";
}
else{
html += "<p>"+data.articles.data[i].body+"</p>";
}
html += "<small class='timestamp'>Written on "+created_at+" by "+data.articles.data[i].user.name+"</small></div></div><hr class='hrStyle'></hr>";
history.pushState(null, null, "/articles?page="+(i+1));
}
for(let i=0;i<data.articles.total;i++){
//console.log(data.articles.data[i].id);
pagination += "<li class='page-item'><a class='page-link' href='/articles?page="+(i+1)+"'>"+(i+1)+"</a></li>";
}
pagination += "<li class='page-item'><a class='page-link' href='#'>Next</a></li></ul>";
}
html+="<div class='d-flex' style='margin: 10px 0px;padding-top: 20px;'><div class='mx-auto' style='line-height: 10px;'>"+pagination+"</div></div></div>";
$('#maine').html(html);
//?page=2
},
error: (data) => {
console.log(data);
}
});
}
When i go to next page, it shows json response as i previously stated. Look in the image above. It won't render ...
In this case ajax response should contain only the real content you want to get with the assynchronous request (html tags inside body). Your #maine element should be a div or another structure capable of having html child tags.
Ps.: If you want to render the ajax response like another page by changing header tags and maybe even the http content type then the response should be load inside an iframe tag.
**Edit: ** In pratice, delete the previous content before body tag in the view returned by ajax. And #maine must be a to contain the ajax response.

Can I use fetch api in jquery-datatables?

I understand that you can use ajax to populate the datatable. But can you use fetch?
Because I have this normal table, filled dynamically using fetch api.
$(document).ready(function(){
fillTable();
})
//fetch api (AJAX) to fill table
fillTable = () => {
fetch('http://localhost:3000/home.json')
.then(response => response.json())
.then(data => {
let html = '';
for (i = 0; i < data.length; i++){
html += '<tr>'+
'<td class="tdUsername pv3 w-35 pr3 bb b--black-20">'+ data[i].username + '</td>'+
'<td class="tdPassword pv3 w-35 pr3 bb b--black-20">'+ data[i].password + '</td>'+
'<td class="pv3 w-30 pr3 bb b--black-20">'+
'<div class="btn-group" role="group" aria-label="Basic example">'+
'<a class="editButton f6 grow no-underline ba bw1 ph3 pv2 mb2 dib black pointer" data-toggle="modal">EDIT</a>'+
'<a class="deleteButton f6 grow no-underline ba bw1 ph3 pv2 mb2 dib black pointer" data-toggle="modal">DELETE</a>'+
'</div>'+
'</td>'+
'</tr>'
}
$('#tblBody').html(html);
})
.catch(err => console.log("ERROR!: ", err))
}
So I am wondering if I can use fetch-api instead of using this to fill the datatable.
//syntax copied from the website
$('#myTable').DataTable( {
ajax: '/api/myData'
} );
It is possible to use 'ajax' option as a function, see https://datatables.net/reference/option/ajax#function
As a function, making the Ajax call is left up to yourself allowing complete control of the Ajax request. Indeed, if desired, a method other than Ajax could be used to obtain the required data, such as Web storage or a Firebase database.
When the data has been obtained from the data source, the second parameter (callback here) should be called with a single parameter passed in - the data to use to draw the table.
Example:
$('#example').dataTable( {
"ajax": function (data, callback, settings) {
callback(
JSON.parse( localStorage.getItem('dataTablesData') )
);
}
});
I was looking for this answer myself as I am trying to stay away from jquery as much as possible, but was unable to find an answer anywhere. I ultimately figured it out on my own and the implementation is not very different than using DataTable's suggested jquery ajax call.
var myTable = $('#myTable').DataTable({
ajax: async function (data, callback, settings) {
let response = await fetch("/api/v1/some/end/point", {headers: {Authorization: 'Bearer ' + sessionStorage.getItem("token")}});
if (response.ok) {
let msg = await response.json();
sessionStorage.setItem('token', msg.token);
console.table(msg.data);
delete msg['token'];
callback(msg);
} else {
console.log(response);
}
},
...... followed by the usual DataTable options
if someone is looking for an answer.
Yes, you can use fetch to populate datatable, here is an example.
fetchEndPointData(dc)
.then(aggregatedData => {
$('#table1').dataTable().api().rows.add(aggregatedData);
}).catch(error => {
// When fetch ends with a bad HTTP status, e.g. 404
console.log(error.message);
});
invoked method
async function fetchEndPointData(dc) {
const response = await fetch('/someEndPoint=' + dc);
const movies = await response.json();
return movies;
}
Note : the fetchEndPointData is returning a promise.
reference : https://dmitripavlutin.com/javascript-fetch-async-await/

Navigate to another Page after appointment has been saved in kendo scheduler

I have got this scheduler displayed but not binding to tasks. The scheduler in the view. I am using java script method to read/create call to web api
#(Html.Kendo().Scheduler<TaskViewModel> ()
.Name("AppointmentSearchScheduler")
.DataSource(dataSource => dataSource
.Custom()
.Schema(schema => schema
.Model(m => {
m.Id(f => f.TaskID);
m.Field(f => f.OwnerID).DefaultValue(1);
}))
.Transport(new {
read = new Kendo.Mvc.ClientHandlerDescriptor() {
HandlerName = "customRead"
},
create = new Kendo.Mvc.ClientHandlerDescriptor() {
HandlerName = "customCreate"
}
})))
Below is javascript handler method I am not including create handler for brevity.
function customRead(options){
//get the selected Row of the kendo grid
var selectedRow = $("#locationgridKendo").find("tbody tr.k-state-selected");
var scheduler = $("#AppointmentSearchScheduler").data("kendoScheduler")
//get SelectedRow data
var rowData = $('#locationgridKendo').data("kendoGrid").dataItem(selectedRow);
if (rowData !== null) {
//Convert data to JSON
var rowDataJson = rowData.toJSON();
//extract the location ID
var locationId = rowDataJson.LocationID;
var CalenderweekStartDate = new Date().toISOString();
baseUrl = $('base').attr('href');
$.ajax({
url: baseUrl + 'Schedular/api/GetAppPerLocation?locationId=' + locationId + '&date=' + CalenderweekStartDate,
type: 'GET',
cache: false,
contentType: 'application/json',
success: function (result) {
//This method is hitting and i can see the data being returned
console.log('data is received : ' + result.Data);
options.success(result.Data);
},
error: function (xhr, status, error) {
//alert("Error: Search - Index.js - submitAppointment()");
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
}
Here is the web API controller called by making ajax call . The controller works perfectly when i used the basic read/create syntax . The ajax call complete and it does hit back the success method and returns the data but scheduler for some reason is not binded to incoming data. Here is my controller code
[HttpGet]
[Route("api/GetAppPerLocation")]
public DataSourceResult GetAppointmentPerLocation([ModelBinder(typeof(Usps.Scheduling.Web.ModelBinders.DataSourceRequestModelBinder))] DataSourceRequest request, int locationId, DateTime date) {
List < TaskViewModel > locationAvailableAppointmentList = new List < TaskViewModel > ();
locationAvailableAppointmentList = data.Select(appt => new TaskViewModel() {
TaskID = appt.ServiceAppointmentId,
Title = "Appointment Available",
Start = DateTime.SpecifyKind(appt.AppointmentBegin, DateTimeKind.Local),
End = DateTime.SpecifyKind(appt.AppointmentEnd, DateTimeKind.Local),
Description = "",
IsAllDay = false
}).ToList();
return locationAvailableAppointmentList.ToDataSourceResult(request);
}
For some reason the scheduler is not binding to incoming data . the incoming data works perfectly when i use a basic binding approach but not using transport . My goal for using this approach is once i am done with read(scheduler is not binding now) , on create I need to grab the ID of the newly created task returned by my controller and then pass that id to another mvc controller to render a confirmation page. Any other approach to accomplish this goal will be highly recommended.
Please excuse me for any mistake since this is my first question on stackoverflow.
My goal for using this approach is once i am done with read(scheduler is not binding now) , on create I need to grab the ID of the newly created task returned by my controller and then pass that id to another mvc controller to navigate render a confirmation page.
I speculated that read was not returning correct result so i had to fix that .Also my basic goal was redirection to another page after with appointment id and displaying a confirmation screen. This is how accomplished it . I understand this is not the best approach but it has been more than a year no body answered by question. Here is the approach i took .
I added a error to the model state like this in my controller
if (!String.IsNullOrEmpty(task.TaskID.ToString()))//redirect to confirmation page if the appointment was added to the queue
ModelState.AddModelError("AppointmentID", confirmationNumber);
then on client side i configure the error event on grid like this
.Events(
events => events.Error("RedirectToConfirmationPage"))
Here is the Javascript method details
function RedirectToConfirmationPage(e) {
console.log('RedirecToConfirmationPage method......');
console.log(e);
if (e.errors) {
var appointmentID = "";
// Create a message containing all errors.
$.each(e.errors, function (key, value) {
console.log(key);
if ('errors' in value) {
$.each(value.errors, function () {
appointmentID += this + "\n";
});
}
});
console.log('Newly Generated AppointmentID = ' + appointmentID);
// Redirect URL needs to change if we're running on AWS instead of on local developer machines
if (window.location.href.indexOf('/TestProject.Scheduling') > 1) {
window.location.href = '/Scheduler/AppointmentConfirmation?confirmationNumber=' + appointmentID
}
else {
window.location.href = '/Scheduler/AppointmentConfirmation?confirmationNumber=' + appointmentID
}
}
}
Hope it is helpfull to someone down the road.

How can I can the scope which the onComplete function is called

I have created a wrapper for the FineUploaderBasic class in order to link it in with my existing system and when the onComplete function is called it is called in the scope of the FineUploaderBasic element and not the parent element.
How can I change this or access the parent of the FineUploaderBasic Instance?
I have written the code using ExtJs as Follow's and I am trying to trigger my own upload complete event once the FineUploader upload has been completed. but the "onUploadComplete" function is being called within the scope of the FineUploader Instance and I am not able to access my own object.
Ext.define('X4.Core.FileUploader', {
mixins: {
observable: 'Ext.util.Observable'
},
uploader: null,
constructor: function (config) {
this.initConfig(config);
this.mixins.observable.constructor.call(this, config);
this.addEvents({
/**
* Event which is triggered once the file upload has been completed successfully.
*
* #since X4 4.1.1
*/
"uploadcomplete": true
});
return this;
},
getUploader: function () {
var me = this;
if (me.uploader === null) {
me.uploader = new qq.FineUploaderBasic({
autoUpload: false,
request: {
endpoint: '/_system/x4/commands/file_uploader.ashx'
},
callbacks: {
onComplete: me.onUploadComplete
}
});
}
return me.uploader;
},
onUploadComplete: function(id, name, response) {
var me = this;
alert('upload complete ' + id + ' ' + name + ' ' + response);
me.fireEvent('uploadcomplete', me.callbackScope, id, name, response);
},
addFile: function (fileInput) {
var me = this;
return me.getUploader().addFiles(fileInput.extractFileInput());
},
upload: function () {
var me = this;
me.getUploader().uploadStoredFiles();
}
});
Since you haven't provided any specific information about your problem, I'm going to have to provide a very generic answer. Also, since you have not specified if you are using the jQuery plug-in or not, I'll have to assume that you are not.
So, the answer to your question really has nothing to do with Fine Uploader. Assuming you are using the no-dependency version, Fine Uploader sets the context of the call to each callback/event handler to the associated Fine Uploader instance. You are asking for the "parent" element, ostensibly the parent element of the value you have specified for the element option.
You can determine the parent of any element/node via the node's parentNode property.

AntiForgeryToken not being received when using plupload in form submission

I'm using Plupload to allow multiple images to be uploaded to an mvc3 web app.
the files upload OK, but when i introduce the AntiForgeryToken it doesn't work, and the error is that no token was supplied, or it was invalid.
I also cannot get the Id parameter to be accepted as an action parameter either, it always sends null. So have to extract it myself from the Request.UrlReferrer property manually.
I figure plupload is submitting each file within the upload manually and forging its own form post.
My form....
#using (#Html.BeginForm("Upload", "Photo", new { Model.Id }, FormMethod.Post, new { id = "formUpload", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.Id)
<div id="uploader">
<p>You browser doesn't have HTML5, Flash or basic file upload support, so you wont be able to upload any photos - sorry.</p>
</div>
<p id="status"></p>
}
and the code that wires it up...
$(document).ready(function ()
{
$("#uploader").plupload({
// General settings
runtimes: 'html5,flash,html4',
url: '/Photo/Upload/',
max_file_size: '8mb',
// chunk_size: '1mb',
unique_names: true,
// Resize images on clientside if we can
resize: { width: 400, quality: 100 },
// Specify what files to browse for
filters: [
{ title: "Image files", extensions: "jpg,gif,png" }
],
// Flash settings
flash_swf_url: 'Content/plugins/plupload/js/plupload.flash.swf'
});
$("#uploader").bind('Error', function(up, err)
{
$('#status').append("<b>Error: " + err.code + ", Message: " + err.message + (err.file ? ", File: " + err.file.name : "") + "</b>");
});
// Client side form validation
$('uploadForm').submit(function (e)
{
var uploader = $('#uploader').pluploadQueue();
// Validate number of uploaded files
if (uploader.total.uploaded == 0)
{
// Files in queue upload them first
if (uploader.files.length > 0)
{
// When all files are uploaded submit form
uploader.bind('UploadProgress', function ()
{
if (uploader.total.uploaded == uploader.files.length)
$('form').submit();
});
uploader.start();
} else
alert('You must at least upload one file.');
e.preventDefault();
}
});
});
and here is the controller action that receives it...
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(int? id, HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var parts = Request.UrlReferrer.AbsolutePath.Split('/');
var theId = parts[parts.Length - 1];
var fileName = theId + "_" + Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return Content("Success", "text/plain");
}
As you can see, i have had to make the id parameter nullable, and i extract this manually in the action method.
How can i ensure that the values are sent with each form post correctly?
short answer : YES!
use multipart_params options like this:
multipart_params:
{
__RequestVerificationToken: $("#modal-dialog input[name=__RequestVerificationToken]").val()
}
short answer: you can't.
What you can do in this case is pass your token either as another multipart paramenter (if using that), or as part of the URL as a GET parameter, but nothing from the form will be sent by plupload as it builds its own request.
Another possibility is using custom headers to pass back the token to the server (plupload has a headers option), but whichever is the method you use, you will have to process it on your backend to validate it.

Resources