Have Controller:
public class MyController : Controller
{
[HttpGet]
public ActionResult MyAction(int iMode, string strSearch)
{
return View();
}
}
In my view I have a div with id=center
I execute the following code in javascript
url = "/MyController/MyAction?iMode=7&strSearch=as";
$('#center').load(url);
When debugger his the breakpoint in my action on first line, iMode variable shows proper value of 7, strSearch parameter arrives as null.
Any help/advice would be most welcome.
Just use the ampersand instead of &
url = "/MyController/MyAction?iMode=7&strSearch=as";
Thanks Innatepirate for the tip. Wasted enough time trying to figure out why controller is getting null values. Replacing & with ampersand did the trick. By the way I was doing the simple age old window.location.href = link and still had the problem. Probably its the MVC parsing and routing that is messing this up.
Related
Is it possible to send a javascript variable to a controller endpoint, and then have the controller return a new view?
I've tried using a requestbody and ajax to do it, which passes the variable correctly, but is unable to load a new view.
Maybe there's a way to do it with thymeleaf?
If you're using Thymeleaf then just reference the template you want to return to the user by its filename.
#Controller
public class YourController {
#GetMapping("/someUrl")
public String getTemplate(#RequestParam String templateName){
return templateName;
}
}
This would be the bare minimum that you'd need, assuming your templates are in the correct folder - by default in resources/static. If the frontend sends a GET (/someUrl?templateName=xyz) to the backend, it would return the xyz.html from your templates. If it does not find the template that was requested in the parameters then it will return a 404.
Edit: Reading through the comments I realized there might be a confusion between #RequestParam and #PathVariable. In case you want to use a path variable to define the template name, so that the frontend can call GET (/someUrl/xyz), then you can do
#Controller
public class YourController {
#GetMapping("/someUrl/{templateName}")
public String getTemplate(#PathVariable String templateName){
return templateName;
}
}
Resources for both below:
https://www.baeldung.com/spring-request-param
https://www.baeldung.com/spring-pathvariable
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.
I want to send the variables itemId and entityModel to the ActionResult CreateNote:
public ActionResult CreateNote(
[ModelBinder(typeof(Models.JsonModelBinder))]
NoteModel Model, string cmd, long? itemId, string modelEntity)
with this javascript:
Model.meta.PostAction = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId, modelEntity = modelEntity});
However, the url being send is
localhost:1304/Administration/blue/en-gb/Entity/CreateNote?modelEntity=Phrase&itemId=44
I want to send
localhost:1304/Administration/blue/en-gb/Entity/CreateNote?modelEntity=Phrase&itemId=44
How can I prevent Url.Action to put the & in front of the second variable that I want to send?
I didn't notice yesterday that you had & I thought that was the SO editor had changed that. Try wrapping your Url.Action() in a #Html.Raw() to prevent the Encode of &.
Or alternatively only Url.Action() the controller/action bit and pass the two parameters as post data rather than directly on the url, jQuery should sort out the &'s for you that way.
I think your problem is with Model.meta.PostAction - is that property a string?
If so then my guess would be that you're adding it to the page with either:
Razor: #Model.meta.PostAction
ASP view engine: <%:Model.meta.PostAction%>
Both of which automatically encode that string for you.
To fix it either use #Html.Raw()/<%= (both of which don't encode) or make the PostAction property an IHtmlString that knows that it's already been encoded:
string actionUrl = Url.Action("CreateNote", new { cmd = "Save", itemId = itemId, modelEntity = modelEntity});
Model.meta.PostAction = new HtmlString(actionUrl);
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.
i am creating mvc application and is it possible to get the url to string somehow?
my url is like:http://localhost:7264/Asortiman/Browse?kategorije=327
and in the head of some view i would like to get this url like string and take last 3 digits in this case 327 and use it as param in my function.
Why dont you do it at the Controller level and send it with the ViewBag dynamic object?
I Suppose your Controller is Asortiman and your Action method is Browse. Then if you define your method like;
public ActionResult Browse(int kategorije){
ViewBag.KategoriJe = kategorije;
return View();
}
Then at the view you can now reach it with the same dynamic object. For further use see the default mvc application project at the vs2010