Passing parameters in redirect view Spring MVC - spring-mvc

I am not able to get how to pass a parameter along with a main url from a controller. I tried like this:
return new ModelAndView(new RedirectView("home?var=ss", true));
But I am getting null value for var . What is the correct way?

The documentation says:
By default all model attributes are considered to be exposed as URI
template variables in the redirect URL. Of the remaining attributes
those that are primitive types or collections/arrays of primitive
types are automatically appended as query parameters.
So you don't have anything to do except making sure that you have a model attribute named var, with the value ss.

Related

Should default POJO parameter resolution add the parameter to the model?

I just spent some time troubleshooting an aspect of Spring MVC's default handler method parameter resolution and I'd like to ask those closer to the project if this behavior is intended or if it'd be reasonable to open a ticket suggesting a change.
The issue has to do with the default resolution of POJO-style objects in method parameters like this:
#RequestMapping("/endpointwithparams")
public String endpointWithParams(EndpointParams params) {
// Do some stuff
return "viewname";
}
With no annotations or custom argument resolvers, Spring will attempt to bind the EndpointParams object by matching request parameters to its field names. It will even run validators if any are configured. This seems great - it lets me write simple POJO objects to organize related sets of parameters without having to have a custom argument resolver for each one.
The part that throws me off is that after the EndpointParams object is created it will also be automatically added to the model. This is because the actual resolver of this parameter will be a ModelAttributeMethodProcessor with its "annotationNotRequired" flag set to true. I don't want this parameter added to the model - its presence causes some trouble down the line - and it certainly wasn't intuitive to me that I should expect that addition to happen for a parameter that wasn't annotated with #ModelAttribute.
This behavior is also inconsistent with what happens when you have a "simple" request parameter like this:
#RequestMapping("/endpointwithparams")
public String endpointWithParams(String param) {
// Do some stuff
return "viewname";
}
In the above example, the String param will be resolved by the RequestParamMethodArgumentResolver, which will not add anything to the model.
Would it be reasonable to suggest that better default logic for non-annotated POJO parameters would be the same binding and validation that currently occurs, but without the automatic addition to the model? Or is there some context I'm missing that makes the full #ModelAttribute behavior the best default choice?

ASP.NET Attribute Routing - Url.Action not working

This code works fine:
[RouteArea("Main", AreaPrefix = "Hello")]
[RoutePrefix("{orgCode}")]
public class ResponseController : BaseController {
[Route("Save/{formCode}/{responseId}")]
public ActionResult Save(string formCode, int responseId, string questionCode){}
}
and Url.Action("Save", "Response") produces, for example, /Hello/org123/Save/form/123
However, if the Route attribute is changed and another segment added:
[Route("Save/{formCode}/{responseId}/{questionCode}")]
then Url.Action("Save", "Response") produces an empty string.
Is there a limit to how many sections can be defined in the route?
Is there a limit to how many sections can be defined in the route?
No.
But MVC only can build URLs using route values that it knows about. This can be a combination of route values that are passed to the Url.Action() method and values that are in the current request (usually passed through the current URL).
When the framework tries to determine which route to use, it selects the first route that matches all of the route values (controller, action, and anything else) and matches all of the (optional) constraints.
The route will not match if all of the conditions below are true for any of the parameters:
Have no defaults
Are not marked UrlParameter.Optional (NOTE: Optional parameters may not have any non-optional parameters to the right of them)
Are not present in the current request
Are not explicitly passed as route values to Url.Action() (or other method that calls UrlHelper to generate a URL)
Have constraint rules that do not match
In short, a route only matches if all of the required parameters are provided and constraints are satisfied.
So, apparently there is no questionCode in the current context, and since it is required to build the URL, you get an empty string. Most likely you need to pass it explicitly.
Url.Action("Save", "Response", new { questionCode = "123" })
You should also be careful to always explicitly pass other parameters if there may be cases where they are not present in the URL.

Symfony2 pass whole entity object to path()

Why I need this?
When I want to change the route from /news/{slug} to /news/{id} for example, I need to replace all places where path('news', {'slug': 'my-post'} is called. I want to pass the entity like so path('news', {'post': post}) and then change the route however I like. This will give me the flexibility to easily change the routes. Thanks.
You cannot pass eneity as param. path function takes only string and number arguments, because this function generate url based on routing.
How do you imagine passing object to browser url bar?
/news/"{object": std_what_the_#?}
Of course you can make your own twig function and pass object to make your url.
This way you can check your object has slug property and choose your route and params. Anyway you have to do it myself.
I hope it help but your question is not clear...

How to create a simple ASP.NET MVC action method that accepts HTTP-POST data?

i wish to have a simple Action in my controller that accepts a few optional values and some integer values.
this is my route i wish to have:
HTTP.POST
/review/create
and this is the Action method i would like...
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Create(int userId,
int addressId,
byte baseScore,
byte reviewType,
string subject,
string description)
{ ... }
I'm under the uneducated impression that all of those arguments above will be populated by the forms collection values ... but it's not happening. Also, I have no idea how I would write a route, to handle those ... because those values are form post data....
here's my global.asax....
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// Api - Search methods.
routes.MapRoute(
"Search Methods",
"{controller}/{action}"
);
In fact, the action method is never called because it doesn't seem to find it :(
But, if create and action without any of those arguments, then it finds it ?????????
How would you write a route and action method to accept some require and some optional arguments, for the route /review/create ?
As far as i can see you may rewrite your controller action like this:
public ActionResult Create(int foo, int bar, byte blah, string name, int? xxx) {
// code here
}
The ModelBinder will then ensure that foo,bar and blah are set. Name and xxx may be null. I can't test it a the moment, but i think return type of the action should be ActionResult.
If you are POST'ing a form, just make sure that the elements in your form (textboxes, checkboxes, textarea, etc) have id's that match the parameters in your method. As an alternative you can pass a FormCollection to the method, and do myFormCollection["foo"] to get a string representation of the value (which can then be parsed to an int).
From my experience, you are missing a number of key elements and concepts with this question.
First and foremost, I don't believe you can execute a POST without a form. The form has to contain the controls from which you pull the values that get passed to the controller method. If the goal is to simply unit test your POST controller method, then just call the method directly in your test, which it appears that you're doing, based on one of your comments. If you involve the view, then you're doing integration testing, not unit testing. Regardless of the test type, the test will always fail because you are choosing not to build the form. Even if you manage to force the POST using Fiddler, Firebug or any other mechanism, you're still not testing the view, you're testing the HTTP protocol.
I highly recommend that you employ a web application testing tool, such as WatiN or Selenium, to test your web pages, rather than throw together a quick-and-dirty test that really doesn't test anything useful.
In your post request set content-type="application/json; charset=UTF-8" and pass the values for the method parameter in JSON format. This should make Asp.MVC not to look in FormCollection for those values.

ASP.Net MVC Json Result: Parameters passed to controller method issue

I'm having a problem getting a controller method that returns a JsonResult to accept parameters passed via the JQuery getJSON method.
The code I’m working on works fine when the second parameter ("data") of the getJSON method call is null. But when I attempt to pass in a value there, it seems as if the controller method never even gets called.
In this example case, I just want to use an integer. The getJSON call that works fine looks like this:
$.getJSON(”/News/ListNewsJson/”, null, ListNews_OnReturn);
The controller method is like this:
public JsonResult ListNewsJson(int? id)
{
…
return Json(toReturn);
}
By putting a breakpoint in the ListNewsJson method, I see that this method gets called when the data parameter of getJSON is null, but when I replace it with value, such as, say, 3:
$.getJSON(”/News/ListNewsJson/”, 3, ListNews_OnReturn);
… the controller method/breakpoint is never hit. Any idea what I'm doing wrong?
I should also mention that the controller method works fine if I manually go to the address via my browser ("/News/ListNewsJson/3").
getJSON expects a set of key/value pairs, not a bare value, so you would need to use { id: 3 } to pass an id value. Unfortunately this will get turned into /News/ListNewsJson/?id=3 which is not what you want. I suggest just appending the value onto the Url to construct it in the route form. I'm also assuming that the value actually comes from a variable so I've written it in that form. If it's possible to be null, then you'll need to do something more complicated to formulate the Url so it makes sense.
var id = '3';
$.getJSON(”/News/ListNewsJson/” + id, ListNews_OnReturn);
i know this is an older thread, but why aren't you using the MVC Url.Action() helper? This would make sure your route is correct.
$.getJSON('<%=Url.Action("ListNewsJson", "News") %>/' + id, ListNews_OnReturn);
Of course, if the id value comes from ViewData you could use the 3rd parameter of the Url.Action() helper method to pass in an anonymous type with an id property, and MVC will create the desired URL. Otherwise, concat it in javascript if the value is coming from the javascript function.
HTH

Resources