ASP.NET Core API POST parameter is always null from Firefox - ajax

In my Angular2 Application, I'm submitting a form and send data through POST API to dotnet core backend. I've created a new form, that is working fine with chrome, but on firefox, I'm receiving null in POST API parameter.
I'm all stuck what to search and how to?? I've checked every possible issue and didn't find anything, because App is working fine with chrome, all data is up to date and correct but a single form is not working on firefox.
Can anyone help me out what to do? because I'm totally stuck and have
no idea what to do??
My Endpoints are;
[HttpPost]
[Route("api/Intimation/SaveIntimation")]
public async Task<ActionResult> SaveIntimation([FromBody] ViewModelCreateIntimation objCreateIntimation)
{
if (objCreateIntimation == null || objCreateIntimation.objIntimation == null)
{
return Ok("null received");
}
// remaining code
}
my service on angular side
saveIntimation(intiModel) {
console.log(intiModel);
return this.httpClient.post<ViewModelResponse>(this.baseUrl + this._SubmitIntimationUrl, JSON.stringify(intiModel), { headers: this.configurations.getHeaderWithAuth() });
}
where this._SubmitIntimationUrl is "/api/Intimation/SaveIntimation", intiModel is object that I'm passing.
Controller function - Angular
this.intimationModel = this.admissionForm.value;
this.adminService.SubmitAdmissionIntimationService(this.createIntimationModel).subscribe(
(response) => {
this.responseModel = response;
// further process
},
(error) => {
this.notification.onClear();
this.notification.onError(this.errorHandler.handleError(error).error, Constants.MESSAGE_ERROR);
}
);
Data that is sending from service (Last place where I can check data)

The problem looks like it's because of the name of the parameter in your controller is different to that being passed up in the request.
In your controller, the parameter the framework is trying to bind to is called objCreateIntimation, but your request shows you're sending up objIntimation instead. As they have different names, the model binder has no idea that objIntimation should be bound to objCreateIntimation.
Give them both the same name, and that should fix it for you.

I went through same issue once, and It took almost a day to figure out the reason behind it,
do check your date pickers and its values, and make sure it is not null and its format is also correct. Because firefox is a bit strict in this matter and a litter change in datepicker makes it null.
hope it helps you.

Related

"the UmbracoHelper was constructed with an UmbracoContext and the current request is not a front-end request."

I'm trying to implement ajax pagination using Umbraco.
On the server side, I have the following:
[System.Web.Http.HttpGet]
public JsonResult pagination(int? page)
{
IEnumerable<IPublishedContent> newsPosts = Umbraco.AssignedContentItem.DescendantOrSelf("news").Children.Where(x => x.IsVisible() && x.DocumentTypeAlias == "newsPost").OrderByDescending(x => x.UpdateDate).Take(5);
//from here on we will be returning the json within which information required for displaying post entries in carousel is included.
string json = "[some random string]"; //just random string for now.
return Json(json, JsonRequestBehavior.AllowGet);
}
As you can see, I'm trying to get necessary data from IPublishedContents, but I'm having trouble instantiating this series of IPublishedContents.
And this is the error I'm getting when I access:
locahost:{port}/umbraco/surface/{controller}/pagination on Chrome.
Cannot return the IPublishedContent because the UmbracoHelper was constructed with an UmbracoContext and the current request is not a front-end request.
Details: System.InvalidOperationException: Cannot return the IPublishedContent because the UmbracoHelper was constructed with an UmbracoContext and the current request is not a front-end request.
As I said, I'm making this request from Chrome, which is I think means this request is from the front end, so I'm not sure why I'm getting this error.
In the course of searching I found these
1) our.umbraco.com forum
2) stackoverflow post
is deserted with no answer, and as for 2, it strikes me that the answer is not quite relevant to my case. I want to instantiate IPublishedContent in the first place.
Mine is Umbraco 7.
and could it be possible to tell me why requests from the front-end are not desirable?
Any hint would be highly appreciated.
Thanks,
Try getting your node this way.
var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
var yourNode = umbracoHelper.TypedContentAtXPath("umbracoPathtoYourNode");
Perhaps easier to use web api
Create a controller which inherits from UmbracoApiController
public class PagedItemsController : UmbracoApiController
{
[HttpGet]
[ActionName("list")] //Optional see note below
public IHttpActionResult GetItems([FromUri] int pageNo = 1)
{
// Next you need some way of getting the items you need.
// I would not return the whole IPublishedContent items. Rather query those and then use linq Select to transform into a more relevant smaller class (not doing this here)
// I've just included this for brevity
var items = _itemService.GetPagedItems(pageNo);
// Now return the results
return Ok(items);
}
}
Calls to endpoints in Umbraco follow the format
/umbraco/api/{controller}/{endpoint}
With the [ActionName("list")] above the call to the GetItems method will be
http://example.com/umbraco/api/PagedItems/list?pageNo=3
Without the ActionName attribute the call would be
http://exampe.com/umbraco/api/PagedItems/GetItems?pageNo=3
With a standard jquery ajax call this will return json without needing to serialise.

Returning a variable from a filter. Laravel 4

I am new to Laravel and I am trying to set up some basic routing logic. I have a route that will process a certain URL pattern. These URLs will usually be an ajax request (returning data for a popup window). However, search engines and users with javascript disabled will follow a normal link, so I want the data to be returned on a separate page. To do this, I need to determine if the request is ajax. I understand I can do this using:
if(Request::ajax()){
//
}
My plan was to do this as part of a 'before' filter attached to the route. If my thinking is correct, I would need to return a boolean ajax=true/false back from the filter. Maybe this is a very simple question, but I can't find anywhere that explains how you actually return a value like this from a filter? Everything I can find seems to assume that the default outcome of any filter logic must be a redirect.
Thanks
EDIT: I've come to the conclusion that I am simply not using the filtering method in the way it was intended, and simply placing the handler in my controller method. But I would still like to know if it is possible to return data from a filter.
In a controller:
if(Request::ajax()){
return Response::json(['message' => 'Hi. Your request was ajax!', 'status' => 1]);
}
The simple solution I found for that is to use Session::flash which populates data for the next request only and you can easily get the result anywhere. So for example :
Route::filter('something', function() {
if(false) {
View:make('error); // or whenever you want
} else {
return Session:flash('result_var', $my_result_var);
}
});

$.extend ignoring 'traditional' flag

I'm working in an ASP.NET MVC4 application, and as such, all array data sent to the server over ajax must be sent using the traditional option. (no [] for POST variables).
The problem is, I also have a filter set-up which requires an AntiforgeryToken to be sent with each ajax POST.
I have fixed this using an ajaxPrefilter like this:
$.ajaxPrefilter(function (options, originalOptions) {
if (options.type.toUpperCase() == "POST") {
options.data = $.param($.extend(originalOptions.data, { __RequestVerificationToken: "antiForgeryToken" }));
}
});
This works great, and adds the __RequestVerificationToken to all POSTs.
However, it also causes my data not to be parametrized according to the traditional flag.
Does anybody know how I can modify my prefilter to account for this?
Example can be found here:
http://jsbin.com/IxoKIKA/2/edit
You forgot to pass the traditional argument to $.param(). You should write:
options.data = $.param($.extend(originalOptions.data, {
__RequestVerificationToken: "antiForgeryToken"
}), true);

Ajax request, should it be POST or PUT

I have created a Spring MVC web app.
The app makes a few calls to the controller. These calls are close/open/end game.
I make these calls using Ajax, so I can handle a response on the top of the page.
ajaxPost = function (url, action, id, onSuccess, onError) {
$.ajax({
type: "POST",
url: url + "?" + action + "=" + id,
success: function(response) {
if(onSuccess !== null) {
onSuccess(response);
}
},
error: function(e) {
if(onError !== null) {
onError(e);
}
}
});
};
The question I have is that I'm using 'POST' for the Ajax request, is that correct, or should it be 'PUT'?
My controller has a default URL, and I'm using the param attribute to decide which method to call, as I have many buttons on the page.
#RequestMapping(params = "open", method = RequestMethod.POST)
#RequestMapping(params = "close", method = RequestMethod.POST)
It doesn't sit well with me that I'm using 'POST' for these calls. Maybe it should be 'PUT'...
Any suggestions? Does it matter?
It depends on what your request should do. So there's no general rule that you should use one over the other, they have different use cases.
POST for creating a record.
PUT for updating an existing record (or putting a record at a specified location/id).
See this wikipedia article for the definitions.
One thing to note is that PUT should be idempotent, doing the same PUT request multiple times should ideally produce the same result as doing a single PUT request. However, POST is not idempotent, so doing several POST requests should (or will) create multiple new records.
So after having read this you should check what your method does, and select the corresponding request method.
Both PUT and POST may create a new record; PUT may also update/change an existing record.
The difference between POST and PUT is that PUT is expected to address the record with it's ID, so that the server knows what ID to use when creating (or updating) the record, while POST expects the server to generate an ID for the record and return it to the client after the record has been created.
Thus, a POST is addressed to the resource as a collection: POST /resource, while PUT is addressed to a single item in the collection: PUT /resource/1
Use POST. Always use POST, unless you're absolutely rock-solid certain that PUT is properly supported by your hosting system.

Debugging Ajax requests in a Symfony environment

Not sure if SFDebug is any help in this situation. I am making an ajax post using jQuery. Which retrieves JSON data in my action URL and then makes a call to the Model method that executes the action. The part until my action URL, and the jQuery call to it work fine. With the data transmitted from the client to the server well received and no errors being made.
It is the part where it calls the method on the Model that is failing. My jQuery method looks like this:
$.post(url, jsonData, function(servermsg) { console.log(servermsg); }) ;
My server action is like this
public function executeMyAjaxRequest(sfWebRequest $request)
{
if($request->isXmlHttpRequest())
{
// process whatever
$servermsg = Doctrine_Core::getTable('table')->addDataToTable($dataArray);
return $this->renderText($servermsg);
}
return false;
}
The method of concern in the Table.class.php file looks like this:
public function addDataToTable($dataArray)
{
// process $dataArray and retrieve the necessary data
$data = new Data();
$data->field = $dataArray['field'];
.
.
.
$data->save();
return $data->id ;
}
The method fails up here in the model, when renderText in the action is returned and logged into the console, it returns the HTMl for SFDEBUG. Which indicates that it failed.
If this was not an Ajax call, I could debug it by seeing what the model method spat out, but this is a little tedious with Ajax in the mix.
Not looking for exact answers here, but more on how I can approach debugging ajax requests in a symfony environment, so if there are suggestions on how I can debug this, that would be great.
You must send cookie with session ide key via ajax
(Assuming you have XDEBUG configured on the server)
In order to trigger a debug session by an AJAX request you have to somehow make that request to send additional URL parameter XDEBUG_SESSION_START=1. For your example:
$.post(url + '?XDEBUG_SESSION_START=1', jsonData, function(servermsg) { console.log(servermsg); }) ;
You can also trigger it via cookie, but appending URL parameter usually easier.

Resources