Clicking Ajax.ActionLink Produces a GET and a POST - razor

Clicking a certain Ajax ActionLink in this app I just inherited produces a POST request AND a GET request (POST and then a GET immediately after). The first request hits the HttpPost method on the server, but the second request (the GET) throws a "404 (Not Found)" error in the browser. How do I stop the unwanted GET request? Where is it coming from?
If I change the method from POST to GET, the reverse occurs with the POST throwing the error instead of the GET.
I searched the application for similar requests to the same HttpPost method that were configured as GETs and there are none.
I searched for custom JavaScript that was attaching an extra click event to all links and there were no instances of that. Could there be other events that would produce the same result in this instance?
Chrome DevTools Screenshot
In DocumentManagementController.cs:
[HttpPost]
public ActionResult OpenPopup(string ntgLoadId) { ... }
In _GridLoadsAddendum.cshtml:
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "DetailedGrid_" + Model.LoadId;
settings.Width = Unit.Percentage(100);
settings.Settings.ShowFilterRow = false;
settings.Settings.ShowGroupPanel = false;
settings.Settings.ShowFooter = false;
settings.Settings.ShowColumnHeaders = false;
settings.KeyFieldName = "NtgLoadId";
settings.Columns.Add(column =>
{
column.FieldName = "Status";
column.Caption = "Status";
column.Width = Unit.Pixel(83);
column.SetDataItemTemplateContent(c =>
{
ViewContext.Writer.Write(
Ajax.ActionLink(
DataBinder.Eval(c.DataItem, "Status").ToString(),
"OpenPopup",
"DocumentManagement",
new
{
ntgLoadId = c.KeyValue.ToString()
},
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ModalContainer",
AllowCache = false
},
new
{
#class = "status-link",
data_Toggle = "modal",
data_Target = "#ModalContainer",
data_backdrop = "static",
data_Keyboard = "false"
}).ToHtmlString());
});
});
settings.Styles.Table.CssClass = "MVCxGridViewTable";
settings.Styles.Header.CssClass = "MVCxGridViewHeader";
settings.Styles.Cell.CssClass = "MVCxGridViewCell addendum";
settings.Styles.CommandColumnItem.CssClass = "MVCxGridViewCell";
settings.Styles.AlternatingRow.CssClass = "MVCxGridViewAlternatingRow addendum";
settings.Styles.PagerBottomPanel.CssClass = "MVCxGridViewPagerBottomPanel";
settings.Settings.ShowFooter = false;
settings.ClientSideEvents.BeginCallback = "initechPortal.carrierPaymentStatusHelper.gridResultsHelper.beginCallback";
settings.CallbackRouteValues = new
{
Controller = "CarrierPaymentController",
Action = "GridLoadsAddendum",
Id = Model.LoadId
};
settings.DataBound = (sender, e) =>
{
MVCxGridView gv = sender as MVCxGridView;
gv.Visible = gv.VisibleRowCount > 0;
};
}).BindToLINQ(
string.Empty,
string.Empty,
new EventHandler<DevExpress.Data.Linq.LinqServerModeDataSourceSelectEventArgs>(
(s, e) =>
{
e.QueryableSource = Model.CarrierPaymentResultData;
e.KeyExpression = "ntgLoadId";
})).GetHtml();

Related

Autodesk.DesignAutomation returning Unexpected token S in JSON at position 0 when calling the workitem api

I am facing a new issue with a fetch
handleSendToForge(e) {
e.preventDefault();
let formData = new FormData();
formData.append('data', JSON.stringify({
Width: this.state.Width,
Length: this.state.Length,
Depth: this.state.Depth,
Thickness: this.state.Thickness,
BottomThickness: this.state.BottomThickness,
rebarSpacing: this.state.rebarSpacing,
outputrvt: this.state.outputrvt,
bucketId: this.state.bucketId,
activityId: 'RVTDrainageWebappActivity',
objectId: 'template.rvt'
}));
this.setState({
form: formData
})
fetch('designautomation', {
method: 'POST',
body: formData,
//headers: {
// //'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
//},
})
.then(response => response.json())
.then(data => { console.log(data) })
.catch(error => console.log(error));
}
and the code for the controller is pretty standard and is slightly modified from one of the forge examples
[HttpPost]
[Route("designautomation")]
public async Task<IActionResult> Test([FromForm] StartWorkitemInput input)
{
JObject workItemData = JObject.Parse(input.data);
double Width = workItemData["Width"].Value<double>();
double Length = workItemData["Length"].Value<double>();
double Depth = workItemData["Depth"].Value<double>();
double Thickness = workItemData["Thickness"].Value<double>();
double BottomThickness = workItemData["BottomThickness"].Value<double>();
double rebarSpacing = workItemData["rebarSpacing"].Value<double>();
string outputrvt = workItemData["outputrvt"].Value<string>();
string activityId = workItemData["activityId"].Value<string>();
string bucketId = workItemData["bucketId"].Value<string>();
string objectId = workItemData["objectId"].Value<string>();
// basic input validation
string activityName = string.Format("{0}.{1}", NickName, activityId);
string bucketKey = bucketId;
string inputFileNameOSS = objectId;
// OAuth token
dynamic oauth = await OAuthController.GetInternalAsync();
// prepare workitem arguments
// 1. input file
dynamic inputJson = new JObject();
inputJson.Width = Width;
inputJson.Length = Length;
inputJson.Depth = Depth;
inputJson.Thickness = Thickness;
inputJson.BottomThickness = BottomThickness;
inputJson.rebarSpacing = rebarSpacing;
inputJson.outputrvt = outputrvt;
XrefTreeArgument inputFileArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/aecom-bucket-demo-library/objects/{0}", objectId),
Headers = new Dictionary<string, string>()
{
{ "Authorization", "Bearer " + oauth.access_token }
}
};
// 2. input json
XrefTreeArgument inputJsonArgument = new XrefTreeArgument()
{
Headers = new Dictionary<string, string>()
{
{"Authorization", "Bearer " + oauth.access_token }
},
Url = "data:application/json, " + ((JObject)inputJson).ToString(Formatting.None).Replace("\"", "'")
};
// 3. output file
string outputFileNameOSS = outputrvt;
XrefTreeArgument outputFileArgument = new XrefTreeArgument()
{
Url = string.Format("https://developer.api.autodesk.com/oss/v2/buckets/{0}/objects/{1}", bucketKey, outputFileNameOSS),
Verb = Verb.Put,
Headers = new Dictionary<string, string>()
{
{"Authorization", "Bearer " + oauth.access_token }
}
};
// prepare & submit workitem
// the callback contains the connectionId (used to identify the client) and the outputFileName of this workitem
//string callbackUrl = string.Format("{0}/api/forge/callback/designautomation?id={1}&bucketKey={2}&outputFileName={3}", OAuthController.FORGE_WEBHOOK_URL, browerConnectionId, bucketKey, outputFileNameOSS);
WorkItem workItemSpec = new WorkItem()
{
ActivityId = activityName,
Arguments = new Dictionary<string, IArgument>()
{
{ "rvtFile", inputFileArgument },
{ "jsonFile", inputJsonArgument },
{ "result", outputFileArgument }
///{ "onComplete", new XrefTreeArgument { Verb = Verb.Post, Url = callbackUrl } }
}
};
DesignAutomationClient client = new DesignAutomationClient();
client.Service.Client.BaseAddress = new Uri(#"http://localhost:3000");
WorkItemStatus workItemStatus = await client.CreateWorkItemAsync(workItemSpec);
return Ok();
}
Any idea why is giving me this error? I have tested the api using postman and it works fine but when I try to call that from a button I keep receive this error. Starting the debug it seems that the url is written correctly. Maybe it is a very simple thing that i am missing.
Cheers!
OK solved...
I was missing to add the service in the Startup and also the Forge connection information (clientid, clientsecret) in the appsettings.json
Now I need to test the AWS deployment and I guess I am done!

POST data to web service HttpWebRequest Windows Phone 8

I've been trying without success today to adapt this example to POST data instead of the example GET that is provided.
http://blogs.msdn.com/b/andy_wigley/archive/2013/02/07/async-and-await-for-http-networking-on-windows-phone.aspx
I've replaced the line:
request.Method = HttpMethod.Get;
With
request.Method = HttpMethod.Post;
But can find no Method that will allow me to stream in the content I wish to POST.
This HttpWebRequest seems a lot cleaner than other ways e.g. sending delegate functions to handle the response.
In Mr Wigley's example code I can see POST so it must be possible
public static class HttpMethod
{
public static string Head { get { return "HEAD"; } }
public static string Post { get { return "POST"; } }
I wrote this class some time ago
public class JsonSend<I, O>
{
bool _parseOutput;
bool _throwExceptionOnFailure;
public JsonSend()
: this(true,true)
{
}
public JsonSend(bool parseOutput, bool throwExceptionOnFailure)
{
_parseOutput = parseOutput;
_throwExceptionOnFailure = throwExceptionOnFailure;
}
public async Task<O> DoPostRequest(string url, I input)
{
var client = new HttpClient();
CultureInfo ci = new CultureInfo(Windows.System.UserProfile.GlobalizationPreferences.Languages[0]);
client.DefaultRequestHeaders.Add("Accept-Language", ci.TwoLetterISOLanguageName);
var uri = new Uri(string.Format(
url,
"action",
"post",
DateTime.Now.Ticks
));
string serialized = JsonConvert.SerializeObject(input);
StringContent stringContent = new StringContent(
serialized,
Encoding.UTF8,
"application/json");
var response = client.PostAsync(uri, stringContent);
HttpResponseMessage x = await response;
HttpContent requestContent = x.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
if (x.IsSuccessStatusCode == false && _throwExceptionOnFailure)
{
throw new Exception(url + " with POST ends with status code " + x.StatusCode + " and content " + jsonContent);
}
if (_parseOutput == false){
return default(O);
}
return JsonConvert.DeserializeObject<O>(jsonContent);
}
public async Task<O> DoPutRequest(string url, I input)
{
var client = new HttpClient();
CultureInfo ci = new CultureInfo(Windows.System.UserProfile.GlobalizationPreferences.Languages[0]);
client.DefaultRequestHeaders.Add("Accept-Language", ci.TwoLetterISOLanguageName);
var uri = new Uri(string.Format(
url,
"action",
"put",
DateTime.Now.Ticks
));
string serializedObject = JsonConvert.SerializeObject(input);
var response = client.PutAsync(uri,
new StringContent(
serializedObject,
Encoding.UTF8,
"application/json"));
HttpResponseMessage x = await response;
HttpContent requestContent = x.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;
if (x.IsSuccessStatusCode == false && _throwExceptionOnFailure)
{
throw new Exception(url + " with PUT ends with status code " + x.StatusCode + " and content " + jsonContent);
}
if (_parseOutput == false){
return default(O);
}
return JsonConvert.DeserializeObject<O>(jsonContent);
}
}
Then when I want to call it, I can use it as following :
JsonSend<User, RegistrationReceived> register = new JsonSend<User, RegistrationReceived>();
RegistrationReceived responseUser = await register.DoPostRequest("http://myurl", user);

best overloaded method match for `RestSharp.Deserialize<RootObject>(RestSharp.IRestResponse)' has some invalid arguments

So i am working this project on Xamarin forms, and get the error as in title on
var rootObject = deserial.Deserialize<RootObject>(gameJson);
I am supposed to return the list of games to my app.How can i remove the error?
public async Task<Game[]> GetGamesAsync(){
var client = new RestClient("http://mystore/");
var request = new RestRequest ("api/Games", Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var apiKey = session ["ApiKey"];
var userId = session ["UserId"];
try
{
request.AddHeader ("authenticationkey",apiKey.ToString ());
request.AddHeader ("authenticationid",userId.ToString ());
}
catch{}
IRestResponse response = client.Execute (request);
statusCodeCheck (response);
var gameJson = response.Content;
if (response.StatusCode == HttpStatusCode.OK) {
RestSharp.Deserializers.JsonDeserializer deserial = new RestSharp.Deserializers.JsonDeserializer ();
var rootObject = deserial.Deserialize<RootObject>(gameJson);
return rootObject.games;
}
else if(response.StatusCode == HttpStatusCode.Forbidden){
return null;
}
}
Not sure you are looking for this but I also using Restsharp in portable library and I'm deserializing datacontracts with Json.NET's JsonConvert.DeserializeObject<T>
method. I have not encountered any problem with it yet.
Also another possible solution is that the returned data is wrapped and the main object is not the RootObject.

View gets Json displayed on the page. not the data

I have an action which returns a JsonResult. The only thing gets displayed on the view is my json which is like
ProcessOrder{"IsValid":true,"url":"/Home/ProcessOrder"}
While debugging the code, I noticed that it gets displayed because of this below line.
var ProcessOrderData = new { IsValid = true, url = Url.Action("ProcessOrder") };
return new JsonResult() { Data = ProcessOrderData };
Can any body please tell me why it gets only json to be displayed on the view?
is something null here that is causing this to get this displayed or any other stuff?
Code:
private ActionResult SubmitAccount(UserAccountModels UserAccountModels)
{
SessionInfo userSession = SiteSetting.Visitor;
if (userSession != null)
{
if (userSession.products.Where(rec => rec.IsAddedToCart).Count() > 0)
{
SiteSetting.Visitor.User.FirstName = UserAccountModels.FirstName;
SiteSetting.Visitor.User.LastName = UserAccountModels.LastName;
SiteSetting.Visitor.User.Phone = UserAccountModels.Phone;
SiteSetting.Visitor.User.Email = UserAccountModels.Email;
var ProcessOrderData = new { IsValid = true, url = Url.Action("ProcessOrder") };
return new JsonResult() { Data = ProcessOrderData };
}}}
It will only display Json because you are returing JsonResult not a View

How to fix the lambda expression delegate error?

I am using this method to get data
private void getNews(int cat_id, int page)
{
this.progress.Visibility = Visibility.Visible;
var m = new SharpGIS.GZipWebClient();
Microsoft.Phone.Reactive.Observable.FromEvent<DownloadStringCompletedEventArgs>(m, "DownloadStringCompleted").Subscribe(l =>
{
try
{
//List<NewsKeys> deserialized = JsonConvert.DeserializeObject<List<NewsKeys>>(r.EventArgs.Result);
ObservableCollection<NewsKeys> deserialized = JsonConvert.DeserializeObject<List<NewsKeys>>(l.EventArgs.Result);
foreach (NewsKeys item in deserialized)
{
items.Add(new NewsKeys { nId = item.nId, title = item.title, shortDesc = item.shortDesc, fullDesc = item.fullDesc, tags = item.tags, smallPic = item.smallPic, bigPic = item.bigPic, video = item.video, audio = item.audio, youtube = item.youtube, doc = item.doc, date_create = item.date_create, date_modify = item.date_modify, date_publish = item.date_publish, catId = item.catId, viewOrder = item.viewOrder, viewCount = item.viewCount, viewStatus = item.viewStatus, viewHome = item.viewHome, uId = item.uId, uFname = item.uFname });
}
}
catch (Exception)
{
MessageBox.Show("Sorry, Some unexpected error.");
}
});
m.DownloadStringAsync(new Uri(Resource.NEWS_API+cat_id+"&page="+page));
}
The error i get is
Error 1 Cannot convert lambda expression to type 'System.IObserver>' because it is not a delegate type C:\Users\Adodis\Documents\Visual Studio 2010\Projects\TV\NewsListPage.xaml.cs 51 133
I have tried all the fixes but unable to fix this problem. Am using the same block in different method in a different class it is working fine but, this method in this class killing me. Please help me if you have idea on this.
Thanks in advance.
Try this (I've separated the Select and Subscribe operations):
var m = new SharpGIS.GZipWebClient();
Observable.FromEvent<DownloadStringCompletedEventArgs>(m, "DownloadStringCompleted")
.Select(l => l.EventArgs.Result)
.Subscribe(res =>
{
try
{
var deserialized = JsonConvert.DeserializeObject<List<NewsKeys>>(res);
foreach (NewsKeys item in deserialized)
{
items.Add(
new NewsKeys
{
nId = item.nId,
title = item.title,
shortDesc = item.shortDesc,
fullDesc = item.fullDesc,
tags = item.tags,
smallPic = item.smallPic,
bigPic = item.bigPic,
video = item.video,
audio = item.audio,
youtube = item.youtube,
doc = item.doc,
date_create = item.date_create,
date_modify = item.date_modify,
date_publish = item.date_publish,
catId = item.catId,
viewOrder = item.viewOrder,
viewCount = item.viewCount,
viewStatus = item.viewStatus,
viewHome = item.viewHome,
uId = item.uId,
uFname = item.uFname
});
}
}
catch (Exception)
{
MessageBox.Show("Sorry, Some unexpected error.");
}
});
m.DownloadStringAsync(new Uri("Resource.NEWS_API" + cat_id + "&page=" + page));