call action method with parameters MVC 4 javascript - javascript

I'm tired and stupid, but heres my coding problem:
We are using d3.js to draw on a google map element in the MVC4 action method called Live.
We have implemented on click for the d3.js element and need to redirect from the javascript to another MVC action method.
the action method "declaration" looks like this:
public ActionResult Visualization(String appId = "", String userId = "")
In javascript we have inside the d3.js function a code snippet that works and looks like this:
.on("click", function (d, i) {
// just as an example use for the click-event.
alert(d.AppName); }
Where d has AppId, and UserId aswell.
What we now want to do is to create a redirect for the click event, calling the action method along with parameters from d. This means when you click the d3.js element you would be redirected to the other page with pre-set parameters.
We have tried things like:
window.location.href = "/StatsLocationController/Visualization/appId=" + d.AppIdentifier + "/userId=" + d.DeviceId
We also tried to use window.location.replace(), but none of it has worked, I guess we haven't figured out the correct syntax for the actionLink, but have a hard time finding examples when googling it. We are thankful for any help we can get!

Instead of:
window.location.href = Html.ActionLink("Visualization", "StatsLocationController", new{ appId=d.AppId, userId=d.UserId}, new{})
Try:
window.location.href = '#Url.Action("Visualization", "StatsLocationController", new{ appId=d.AppId, userId=d.UserId})'
This is assuming you have your routing set up appropriately?
Edit:
The sort of routing that would make this work is something like:
routes.MapRoute(
"MyRoute",
"{controller}/{action}/{appId}/{userId}",
new {
controller = "Home",
action = "Index",
appId = UrlParameter.Optional,
userId = UrlParameter.Optional
});
Second Edit
I've just noticed that you're calling your controller StatsLocationController - Unless your C# class is called StatsLocationControllerController - this is wrong. Asp.Net MVC assumes that for a controller, there will be a class called StatsLocationController and so you should reference your controllers without the Controller part. So in this example your controller should be called StatsLocation which would make the URL look like this:
#Url.Action("Visualization", "StatsLocation", new{ appId=d.AppId, userId=d.UserId})

I forgot I left this without accepting an answer.
simonlchilds have figured out the problem, that we included the Controller in the call.
So the final call looked like:
window.location.href = "/StatsLocation/Visualization/appId=" + d.AppIdentifier + "/userId=" + d.DeviceId
where StatsLocation is the name of the controller.
Such a silly mistake, but at least it had a simple solution and maybe it can help someone.

Related

jQuery button click + spring mvc navigation

So my problem in short: I have some html page with a button. When the button is clicked, I would like to move to another page. Looks pretty simple, but I can't figure it out.
So, my button handling logic looks like this:
$("#go").click(function() {
var source = $("#dropdown").text();
$.ajax({
type : "GET",
url : "mainpage.html",
data: {provider: source}
});
})
Now my controller looks like this:
#Controller
public class MainController {
#RequestMapping(value = "/hello", method = RequestMethod.GET)
public ModelAndView hello() {
ModelAndView mav = new ModelAndView();
mav.setViewName("index");
return mav;
}
#RequestMapping(value = "/mainpage", method = RequestMethod.GET)
public String goToMainPage(#RequestParam("provider") String provider) {
System.out.println("##########################" + provider.trim());
return "empty";
}
}
So the story starts on the page associated with /hello (=index.jsp). The page is found, displayed, everything is all right. However, when I click y button, I can see the bunch of '#' signs printed out, but the page for /hello (index.jsp) is displayed again instead of the one for /mainpage (which should be empty.jsp the file is right there next to the other).
I also tried to return a ModelAndView, but that did not help. I tried to split this controller into two, but it did not help. I tried to use POST instead of GET, you know what happened...
This may be a stupid question, but I'm completely new to Spring MVC.
Ok, finally I figured it out.
I changed my jQuery function to this:
$("#go").click(function() {
var source = $("#dropdown").text();
window.location.href='/mainpage?provider='+source;
});
and controller method to GET.
This also goes through the MVC controller and correctly fetches the value for provider.
Anyways, please let me know if there's a better way to do this.

AngularJS send window.location to a function or a directive

I'm trying to create a "Back" button as a function or directive. Upon clicking it, it would call a function that has several things to do before redirecting the user to a url.
Normally, in pure JS, I would have a simple div with an onclick function to which I would pass the URL to go to then the function would do its thing then make a window.location.href = url and it would be ok.
Here in angular, the URL i'm trying to send is part hardcoded, part coming from a ng-model: url="#/clients/editer/{{client._id}}"
When trying to use a simple function to which I would pass this as a string, my function doesent get the client.id as a string though the HTML inspector of firefox says it does. But if I console.log the URL the function gets, it says
"#/clients/editer/{{client._id}}" instead of "#/clients/editer/56684b4fe7b59ff020b85590"
When trying to use a directive instead of a function, as being new to all this, I dont understant how I'm supposed to pass thir URL to the directive. Since the URL could change radically from a module to another (from "#/clients/editer/{{client._id}}" to "#/materiel/editer/{{materiel._id}}", I need to pass the decoded URL directly to the directive which would then execute the onclick function.
Hope someone can help me !
I made simple test code
js
scope.client._id = 9;
scope.somefunction = function (url){
console.log(url)
}
Html
<div ng-click="somefunction('#/clients/editer/{{client._id}}')">link</div>
Result: #/clients/editer/{{client._id}}
<div ng-click="somefunction('#/clients/editer/'+ client._id)">link</div>
Result: #/clients/editer/9
Is this the result you wanted to achieve?

calling an Action using javascript

Fairly new to the PLAY Framework and because of restriction at my work we are using the 1.2.5 version, and while up til now was able to do all my process using the regular process from HTML to Controller via form submit. I would like to call an Application.Action from a JavaScript function.
While I have a form where information is inputted, another non-submit button could be clicked to go on a separate page for extra information. I want to call a JavaScript function via the "onClick" and inside the JavaScript function call the "#Application.Action(some param...)".
I need to get what is in a particular input field before calling the action.
I tried to do that with a PLAY "popup" but that does not seems to work as I can't pass the parameters along.
so here is the snippet I have:
in HTML file (extends the main.html who has all the javascript file "include")
<form>....
some input fields here
submit button here
</form>
<button onclick="myFunction()" data-role="button" style="width: 5em">Click here</button>
in the JavaScript file that is included in main.html I have something like this
function myFunction() {
var inputField1 = document.getElementById('inputField1').value;
var inputField2 = document.getElementById('inputField2').value;
var inputField3 = document.getElementById('inputField3').value;
window.location = "#{Application.moreInfo(inputField1, inputField2, inputField3)}";
}
Of course that does not work
Is there a way to do it like that?
Do I have to create a route for that?
I was able to reach a separate page by replacing
window.location = "#{Application.moreInfo(inputField1, inputField2, inputField3)}";
with
window.location.href='/goThere';
as long as I have a route
/goThere Application.goThere
but I could not figure out a way to pass parameters, I tried to set the route like
/goThere/{inputField1}{inputField2}{inputField3} Application.goThere(inputField1...)
but I guess I do not have the right syntax either.
Is there a way to call an Application.Action and pass it parameters/fields from a JavaScript function.
Any help is appreciated
The built-in #{jsAction /} template tag does exactly what you want.
Example:
Assume you have a route
GET /moreinfo/{foo}/{bar} Application.moreInfo
You can use the result of jsAction to get the correct URL with the parameters you want:
var fieldOne = "I'm a Javascript variable";
var fieldTwo = "Really? Me too";
var moreInfoAction = #{jsAction #Application.moreInfo(":foo", ":bar") /};
// and since it looks like you want to set the current location
// to your freshly obtained URL:
window.location.href = moreInfoAction({"foo": fieldOne, "bar": fieldTwo});

I want to call javascript function in url.action as parameter in ASP.Net MVC?

Url.Action("actionName","ControllerName",new { extraData = getdata()});
getdata() is a javascript funcion and I want to use it like
public ActionResult actionName(string extraData)
{
*/ bla /*
}
Has anyone any Idea?
Javascript is client side and C# is server side so that is not going to work. It looks like you're using MVC, so why not create a route for this situation? Then the url can be manipulated with javascript on the client, and your server code remains the same.
routes.MapRoute(
"newRoute", // Route name
"NewRoute/{extraData}", // URL with parameters
new
{
controller = "ControllerName",
action = "ActionName",
extraData = string.Empty
}
);
Then on the client you may have a link as below:
<a id="myLink" href="about:blank">My Link</a>
And you can use your javascript to manipulate this link as required:
document.getElementById("myLink").href = "/NewRoute/" + getData();
I've had to make many assumptions here, so if this doesn't answer your question then you might need to add a little more detail about what you're trying to do.

What is the right pattern for using JQuery Ajax and ASP.Net Mvc?

I'm very new to both the Mvc framework as well as JavaScript and JQuery. I'm trying to understand the right way to structure Ajax calls.
Let's say I have a Vote Up button similar to what you see on StackOverflow. When the user clicks it I need to update the vote count in the database and return the new value to the UI. Currently I am achieving this by having an action called VoteUp on the PostsController which takes an int postID as a parameter.
public PostsController : Controller
{
public ActionResult VoteUp(int postId)
{
//Increment Post Vote Count
return Json(voteCount); //Return just the new vote count as a JSon result.
}
}
I'm then calling this method via ajax by invoking the url "http://example.com/posts/voteUp?postId=5". I then return an JSon ActionResult with the new value to update the UI with.
Is this the right way to implement this? Again, I'm totally new to both javascript and jquery. I'm used to doing everything as click event handlers in asp.net webforms. Any guidance would be appreciated.
Yes, it sounds like you've got it about right.
Note, however, that if you change postId to Id, then you could call with a URL like:
http://example.com/posts/voteUp/5
(With the default routing.) It's a question of personal preference.
I would approach this using jQuery and JsonResult Controller. Your jQuery code would call the JsonResult which would pass the pertinent information off to the model code to handle adding a new vote. I wrote a brief tutorial on similar concepts which is available at http://www.dev102.com/2008/08/19/jquery-and-the-aspnet-mvc-framework/

Categories

Resources