What Goes in the Controller for an AJAX get request in GRAILS - ajax

I have an AJAX call in my view,
var ajaxData= $.ajax({
type: "GET",
url: "${createLink(controller:'profile',action:'ajaxList')}",
success: function(data) {
}
});
I created a method in the ProfileController.groovy class in order to return "data" from this call, but I don' know how to format the controller correctly. Here is what I want to return. The model, profile, has a name and a description. I want to return a hash object where the key is the name and the value is the description. Is there a way to do this in the controller so that this ajax call returns that hash. Any help would be aprpeciated. Thanks!

In your controller's ajaxList action build your model as you want it, as usual, and then instead of return model at the end you want to render model as JSON.
For example,
class ProfileController {
def ajaxList() {
def profiles = Profile.list()
def model = profiles.collect { [(it.name): it.description] }
render model as JSON
}
}
And if you want to use the same list action for returning different formats, look at using withFormat.

Related

AspNetBoilerplate Ajax repose error despite 200 response code

Im having some unexpected problems with a ajax call within the aspnetboilerplate system.
I want to return an array to populate a select list,
The ajax call fires correctly and hits the controller. The controller returns the results as a model successfully, except it continually hits an error.
here is my controller action:
public async Task<List<DialectDto>> GetAllDialects(int Id)
{
var language = await _languageAppService.GetLanguage(Id);
return language.Dialects;
}
Here is my ajax call
var languageId = $(this).val();
abp.ui.setBusy('#textContainer');
$.ajax({
url: abp.appPath + 'Language/GetAllDialects?Id=' + languageId,
type: 'POST',
contentType: 'application/json',
success: function (content) {
abp.ui.clearBusy('#textContainer');
},
error: function (e) {
abp.ui.clearBusy('#textContainer');
}
});
Inspecting the return object in javascript clearly shows a 200 result with all the data in the responsetext property.
Other posts suggest that the content type isnt specified correctly and this is likely the a json parse error. Ive tried setting the dataType property to both 'json' and 'text' but still get the same response
I just had the same problem in one project. I'm using AspNet Boilerplate on a web .NET5 project.
Just like in your case I had a call to a controller method in my JavaScript code that returned 200 code, while in JS I had a parse error and then the "success" code was not executed. To solve the problem I changed the return value of my controller method. I used to return an IActionResult value (i.e. the Ok() value for ASP.NET). Then I changed the return value to another object (a DTO in my case) and everything went right afterwards. For reference:
Before (not working):
[HttpPost]
public async Task<IActionResult> Method([FromBody] YourClass input)
{
// method logic
return Ok();
}
After (working):
[HttpPost]
public async Task<DtoClass> Method([FromBody] YourClass input)
{
// method logic
return dtoClass;
}
I also tested that returning a JsonResult class works with the framework just like this (e.g. return new JsonResult(result)).
Hope this helps somebody else in the future :)

How to return a string in a class based view using ajax

I want to transmit a string from a class based view to the client via ajax.
Here's my view, which inherits from another view
class TeamCreateView_Ajax(TeamCreateView):
def render_to_response(self, context, **response_kwargs):
return HttpResponse("asdf")
For some reason, this transmits the entire web page that would've been rendered by TeamCreateView instead of the string "asdf".
class TeamCreateView_Ajax(TeamCreateView):
def dispatch(self, request, *args, **kwargs):
return HttpResponse("asdf")
On the other hand, this correctly transmits "asdf".
What gives?
Usually, using ajax, we communicate using either json/xml to send information from server to webpage. For example:
class SomeView(TemplateView): #I used template view because it has get method
def render_to_response(self, context, **response_kwargs):
data = {}
data['some_data'] = 'asdf'
return HttpResponse(json.dumps(data), content_type="application/json")
And in Script:
$.ajax({ url: url,
type: "get",
success: function (data) {
alert(data.some_data);
})

Ember model hook in Route vs Ember.Object.extend({})

What's the difference between using the model hook in an Ember Route:
App.PhotoRoute = Ember.Route.extend({
model: function(params) {
return Ember.$.getJSON('/photos/'+params.photo_id);
}
});
Versus creating your own Ember Object?
App.PhotoModel = Ember.Object.extend({});
App.PhotoModel.reopenClass({
find: function(id){
$.ajax({
url: 'https://www.go.get.my.photo',
dataType: 'jsonp',
data: { id: id },
success: function(response){
return response.data;
}
});
}
});
Why would you use one over the other?
One is part of the workflow and the other is a class.
The model hook will provide the model for a route when it's accessed (in that case photo). Additionally it will wait for the async call to complete and use the result of the ajax call.
Example: http://emberjs.jsbin.com/
Extending Ember.Object will define a class for reusability. It's very much a building block for the entire Ember framework.
App.MyModelObject = Ember.Object.extend({});
A more useful example would be
App.MyModel = Ember.Object.extend({
total: function(){
return this.get('val1') + this.get('val2');
}.property('val1', 'val2')
});
var foo = App.MyModel.create({val1:3, val2:5});
console.log(foo.get('total'));
Example: http://emberjs.jsbin.com/xinozi/1/edit
The two are completely different. model on an Ember route is a hook which ember gives you to (fetch data from an api and create an object that holds the data your controller needs and so on) return a promise which gets resolved to the route's controller's model, when the said route is entered and transitioned into. On the other hand, App.MyModel = Em.Object.extend({}) creates a class which is just a template from which objects which are instances of App.MyModel can be instantiated.
If your application wanted to model users, for example, it would have a user "model" like
App.User = Em.Object.extend({username: 'Alice'})
or something similar. However, if you have a user route which looks like /#/user/id, then the model hook on the route would be something like this
model: function(params) {
return new Ember.RSVP.Promise(function(success, failure) {
//make an ajax call and invoke the success and failure handles here appropriately
});

How do I cause an MVC controller to redirect the user from an ajax call?

I am sending an array as the "data" value (parameters) of an ajax call to an MVC controller. The controller should then redirect the user to a new page but it does not. Instead I can see in the Preview window that the View is being returned but through the ajax return. I am not sure if the way I am approaching this is correct because I seem to be having a hard time finding good examples to follow. I wanted to avoid an Html.ActionLink because I will have about 20 parameters to pass to the controller.
Here is the function that sends the array to the controller:
submit: function () {
var data = {
"ReqDepartment": (viewModel.reqDepartment === null) ? null : viewModel.reqDepartment,
"EquipmentGroup": (viewModel.equipmentGroup === null) ? null : viewModel.equipmentGroup,
"SiteCode": (viewModel.site === null) ? null : viewModel.site.SiteCode,
}; //header
$.ajax({
type: "POST",
url: "/ArctecLogisticsWebApp/Requisitions/ReqsSummary/",
data: data,
traditional: true
});
}
Here is the controller, ReqSearchCriteria is a ViewModel :
public ViewResult ReqsSummary(ReqSearchCriteria criteria)
{
return View("ReqsSummary", requisitionsRepository.GetReqsAdvancedSearch(criteria));
}
The controller is returning the View in the ajax call. Should I use a different approach to send an array to the controller?
ajax calls won't redirect by themselves. what you need to do is return json from the controller to the view with the result of the action and if the action is successful then redirect
$.ajax({
type: "POST",
url: "/ArctecLogisticsWebApp/Requisitions/ReqsSummary/",
data: data,
traditional: true,
success: function(result){
if(result.Success){
window.location = '#Url.Action('Action', 'Contorller')';
}
}
});
Edit:
The controller method you have will work. It should be a different name from the form you are redirecting from to eliminate confusion. Through data you can pass any information that you need.
data: { id: $('.id').val() },
something like this will pass whatever value is in the field with class id. then on your controller create the model for the view and return view. I use ajax calls everywhere, they are incredibly useful. Please let me know if you have any other questions.
You don't have to check for a result in your success/done handler and then do the redirect manually. You can actually return a JavascriptResult from your controller and it will redirect for you:
$.ajax({
type: 'post',
url: '/Home/DoStuff'
});
[HttpPost]
public ActionResult DoStuff()
{
return JavaScript(string.Format("window.location='{0}';", Url.Action("About")));
}
If you wanted to get fancy you could even create a new ActionResult type that took care of the formatting for you. Or you could detect if it is an AjaxRequest and determine if you should do a RedirectToAction or a JavaScript result.

Controller action method call have the parameter as NULL while calling javascript in MVC3

I use MVC3.
I have `
function userLocation_change()
{
var text = $("#userLocation").val();
alert(text);
var url = '#Url.Action("GetAllLocations", "Home")';
var data = text;
$.post(url, data, function (result) {
});
}
`
Here is my controller action:
public JsonResult GetAllLocations(string userlocation)
{
///...some code...
return Json(..Something.., JsonRequestBehavior.AllowGet);
}
The problem is whenever the controller function is called "userlocation" parameter does have a NULL value. I want the data value would be passed to the controller action.
Could somebody plz tell me why this happens? Any update would be much appreciated.
Thanks.
You need to pass the parameter to the #Url.Action specifically via this overload method for Url.Action. You can use the RouteValueDictionary inline constructor with to instantiate.
Edit: realize now that you need that link to be populated at run time, but the Url.Action method generates the link at render time. I would suggest adding it to the query string and then reading it from the query string in your controller method. I suspect there is a more elegant way.. but I know this works.
something like: var url = '#Url.Action("GetAllLocations", "Home")?userlocation=' + $("#userLocation").val();
Modify your jQuery post function call as:
$.post(
url,
{ userlocation: text },
function(result){
....
});
This is because, you have to send data to the Controller's action method using JavaScript literal. You can view the full listing of different ways to call Controller's action using JavaScript here: http://www.asp.net/ajaxlibrary/jquery_posting_to.ashx
Your action has a string input parameter named userlocation, hence while sending the data to the action, you should specify this, like done in the code below.
Here I am using data: { userlocation: text},
function userLocation_change()
{
var text = $("#userLocation").val();
var url = '#Url.Action("GetAllLocations", "Home")';
$.ajax({
url: url,
type: 'POST',
data: { userlocation: text},
success: function (result) {
}
});
}
Hopes this solves your null problem.

Resources