Grails javascript call controller method - javascript

In a grails view I need to call a javascript method to get some info and so I have a submit action like this:
<input type="submit" name="submit" class="submit action-button" value="Generar" onclick="generateReport()" style="float: right" />
and at the end of the generateReport() I need to call/redirect to the show action of a Controller (because I'm at the create action already)
I'have tried with
1) var jSon = generateJSON();
<g:remoteFunction controller="report" action="show" params="[data:jSon]" />
2) var jSon = generateJSON();
<g:remoteFunction controller="report" action="show" params="[data:${jSon}]" />
1) data reaches null
2) compile error:
org.codehaus.groovy.grails.web.taglib.exceptions.GrailsTagException
Message
Attribute value quote wasn't closed (controller="report" action="show" params="[data:${jSon}]").

you can try this..
declare a variable in your gsp like this..
<script type="text/javascript">
var yourVariable = "${createLink(url: [controller: 'yourController', action: 'yourAction'])}";
</script>
then in your js file..you can use ajax.
example ajax
function checkUsernameAvailable(user, example){
$.ajax(
{
url: yourVariable, <- this variable take from your gsp
contentType:"text/json",
type: "get",
data: ({ id: usernamenya}),
dataType: "json",
cache: false,
async: false,
success: function(data) {
//do something here
},
error: function(xhr) {
}
});
}

var json cannot be assigned to data as params in , as var jSon is a javascript variable. Data in params attribute requires model parameter coming from controller.
In 1st option when it is assigned as params as it is not a model parameter from controller its showing null.
2nd option would not work as this is not the way to define model parameter from controller so giving compile error.
So you should better try getting jSon as model from controller and then define as params.
Or you can follow this link to define g:remoteFunction in onclick itself
http://grails.github.io/grails-doc/2.2.1/ref/Tags/remoteFunction.html
Hope this helps! Thanks.

The remoteFunction tag won't work for your situation because it's rendered into html and JavaScript (server side) before the value of jSon is known (client side).
You'll have to do the ajax call on your own (ex. Jquery).

Related

Pass data from JavaScript function as an object parameter to #Html.Action() C#

Here is what I am trying to do. I want to be able to call an html action and pass in some data as an object parameter. The only thing is this data needs to be returned from a javascript function.
Here is what I am trying to do:
#Html.Action("someAction", "someController", new { passedData = GetDropDownData() })
<script>
function GetDropDownData() {
var data = "test";
return data;
}
</script>
Basically I am trying to pass some drop down data from a control to a partial view being rendered with the #Html.Action(). I want to be able to pass this string to the partial view somehow so I figured I could use JS to pull the drop down data and return it as an object parameter when rendering the page?
Let me know if you have any suggestions or a better way to go about this.
Thank you!
This is not possible the way you're doing it, because razor views are compiled on server side, while javascript is client side. Therefore, the views are already compiled, while javascript runs during runtime. One way to do it is to use ajax to pass variables from javascript to an action in the controller as query parameters or body values. You could achieve that by creating a button or link:
<a href='#' id='clickMe'>Click me</a>
And hooking up jQuery to do the job:
<script>
$(document).ready(function(){
$('#clickMe').click(function(){
$.ajax({
type: "POST",
url: '#Url.Action("Action", "Controller")',
data: {
passedData: GetDropDownData()
},
success: function(response){
$('#placeholderForPartialView').html(response);
}
});
});
});
</script>
It would look something like this depending on your method (GET or POST) type.
Here I assume that you return Partial view as a result and replace the contents of #placeholderForPartialView div with the returned view. Please correct me if I'm wrong.

Making an AJAX request to an MVC controller and getting the data from the response in js

On button click I am trying to send a product name value that the user enters into a textbox to the server to be modified and then back to the page using AJAX. I am getting into the ChangeName method in the controller but not getting into my success function to alert the new name.
The JS:
$("#changeNameButton").click(function () {
var productName = $("#Name").val();
$.ajax({
url: '/Products/ChangeName/',
type: 'POST',
dataType: 'JSON',
data: {name: productName},
success: successFunc
});
});
function successFunc(data) {
alert(data);
}
The controller:
public string ChangeName(string name)
{
string changedName = ChangeNameHelper(name);
return changedName;
}
If anyone can give recommendations on the proper way to make asynchronous calls to a controller in MVC5/6 this would be great.
My main problem is that I am never getting into the successFunc() on response.
Regarding your comment, if you return just a string MVC will convert that to json.
Now, in your updated code you still call a method inside itself. Please call string changedName = ChangeNameForResult(name); or any function with another name.
Install Newtonsoft.Json via nuget package manager and in your controller do this
Public ActionResult ChangeName(string name)
{
// get your object you want to serialize let's say res
return JsonConvert.SerializeObject(res);
}
I needed to set dataType: 'text' rather than JSON since I am returning a simple string.
dataType is the type of data being returned and contentType is the type of data being sent.

Correct jQuery syntax for doing a $.post with a header (ASP.NET MVC)

I'm working on a ASP.NET MVC project that uses some jQuery on the client side. I have a jQuery call like this, which works correctly:
$.post($('form').attr("action"), $('form').serialize(), function(data){
// Deal with the data that came back from the ASP.NET MVC controller
}
I want to do the exact same call, except I also want to send in a custom header. I am able to successfully create and send a custom header like this:
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;
$.ajax({
url: "/report_observation/" + submitType,
cache: false,
type: "POST",
data: {
'viewModel': $('form').serialize(),
},
headers: headers,
success: function (data) {
// Deal with the data that came back from the ASP.NET MVC controller
},
error: function (response) {
alert("Error: " + response);
}
});
There are two problems with this second bit of code. One is that I have to make a custom url to go to the correct controller, and I don't know of a way to simply use $('form').attr("action") to automatically go to the correct place.
The second -- and bigger -- problem is that I'm not able to pass over the form data with $('form').serialize() as I could in the one liner $.post example. Doing a #Html.Raw(Json.Encode(Model)) in my Razor cshtml file doesn't send over the model for the whole form, presumably because this code is within a partial view that doesn't know the state of the models in the other partial views that make up this form.
Anyway, I'm thinking there must be an easy way to take this code...
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers['__RequestVerificationToken'] = token;
...and incorporate the headers property into this bit of code:
$.post($('form').attr("action"), $('form').serialize(), function(data){
// Deal with the data that came back from the ASP.NET MVC controller
}
However, I can't figure out the correct syntax. Any ideas?
OK, I figured it out. The second example can indeed work if the data field looks like this:
data: $("form").serialize(),
In other words, I had to NOT assign it to the viewModel parameter.
yes, for the second problem use that dev5000 says, and, for the URL, simply get the value for the attribute action fo the form and use it:
var url = $("from").attr("action");
$.ajax({
url: url,
...
})

passing javascript parameter to asp.net

I have a Javascript function and i want to pass a parameter from javascript to asp.net. my sample code like below:
function ConfirmMessage(message) {
var msg = "<%= Efe.UI.WebApplication.AppCode.HelperClass.GetScreenMessage(message); %>"
alert.confirm(msg);
}
But I am getting error at "message" parameter. The error is:
The "name" does not exist in the current context.
How can I pass parameter from javascript to asp.net?
You cannot pass parameter from javascript to server side at inline code.
You should use jquery ajax for that.
var message = "value";
$.get(
url: "/yoururl/GetScreenMessage",
data: {message : message},
success: function(data){
alert(data);
});
You're trying to dynamically call a server side function with a parameter, but the <%= %> part is actually a Response.Write. So, during the page load the page will try to render with the Efe.UI.WebApplication.*xxx* method's output.
That won't work.
You'll need a different solution all together. Most likely you'll want to use a "REST-like" service call to get the result of the "message" parameter. I would suggest you take a look at AJAX : http://msdn.microsoft.com/en-us/library/bb398874%28v=vs.100%29.aspx and http://www.codeproject.com/Articles/29400/Ajax-Quick-Start-FAQ

Passing data from ASP.NET View to a Controller Async using JS in .NET core

I want to preface that I know this question has been asked before, but I haven't found a concrete answer that works on .NET core.
I am trying to pass a Model Value back to my controller so I can do some work on it. Can I use Razor URL helpers to send the URL as #Url.Action("Action", "Controller") within the .ajax URL? Also, how can I send data to do work on async? Here is my script file:
$('#ajaxBtn').on('click', function (e) {
$.ajax({
url: "/Home/AjaxReturn",
type: "POST",
dataType: "json",
data: 'data: 12345',
success: function () {
}
});
});
Here is my Controller code:
[HttpPost]
public void AjaxReturn(JsonResult data)
{
var thisData = data;
}
** I am using this for a responsive js datatable (datatables.net) eg. on a DELETE click I want to pass the ID back to the controller so I can delete the record and then pass back a status.
try to change the parameter in your ajax code.
data: '"data": "12345"',

Categories

Resources