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

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

Related

ErrorBinding Spring portlet MVC

Disclaimer: I wished I had a through understanding before starting working with the framework.
But as it is of now, I'm lacking on that front, and hence the question.
I am working with Spring-Portlet MVC.
I have a flow, where in I take an input on a screen, validate the input, depending upon its result it either render same screen or next screen.
Implementation detail:
I have an action method which takes form backed command object. It checks whether entered input is valid or not. If it is not valid, it populate error message in BindingResult instance it takes as another argument.
We have different render method, to render different screen.
I'm taking command object as an argument in these render method. This command object I'm receiving is same as one passed to action.
Problem:
While rerendering a screen spring-mvc should bind the error message populated in action method. Currently when I take command object as argument in render method spring-mvc is somehow unable to bind that error message. But interesting enough it is able to bind the error message if I don't take command object as argument in render method and rather create a new command object altogether there.
can,some one having better understanding of spring-portlet mvc please explain this behaviour, or tell where I am lacking in understanding.
Regards,
Mawia
EDIT: Just to enrich the below answer: Though I didn't exactly isolated the issue which was causing the said behaviour, but the way I met my requirement was using modelattribute. ModelAttribute can be used either on method or a parameter to a method. It ensures that model will made available to all the call till the view is render(that is my understanding!). So we don't need to take command object as parameter in Render method, just annotate the commandObject parameter in action method with ModelAttribute and then you can get the same object returned from model as suggested in the answer below.
I don't think the command/model object should be an argument/parameter in the render method. I have had the same issue trying to get the validation error messages when command/model is defined as argument in render method signature. I typically have the command/object creation/populate in a separate method, like this:
#ModelAttribute(value="address")
public Address getAddress(#RequestParam Integer id){
Address address = null;
if(id != null){
address = myService.getAddress(id);
}else{
address = new Address();
}
return address;
}
If I still need to access the ModelAttribute/command object from the render method, I typically get it by:
#RenderMapping
public String showAddressPage(ModelMap modelMap){
Address address = modelMap.get("address");
//make any additional changes to address
}
I used this example as reference article

Passing parameters in redirect view 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.

WebMethod (sometimes) returns entire website

I have a WebMethod which accepts one parameter.
When I send a request to the webmethod without any parameters everything works well but when I supply a parameter to the same method, it returns entire site instead of a string.
The page parameter changes nothing except the content of the list.
List is just ListView which displays list of strings.
When I use URLRewriting the URL is different in instances that I supply a parameter from instances when I do not.
Can anybody help me with this problem?
My WebMethod:
[WebMethod]
public static string GetResult(int id)
{
return "Hooray";
}
My web method call:
PageMethods.GetResult(docId,
function onSuccess(list) {
$(element).parent().siblings().filter(":first").append(list);
});
URL without parameter:
www.mywebsite.com/items is rewritten to www.mywebsite.com/items.aspx
URL with parameter:
www.mywebsite.com/items/1 is rewritten to www.mywebsite.com/items.aspx?id=1
Here's a discussion about your same issue that might shed some light on the situation. Basically, what it says is that it's not working because the handler that deals with PageMethods is looking for {pagename.aspx}/{methodname}, and your url rewriting is causing it to not recognize you are calling a page method.
One suggestion on that page was to add the following in your javascript code somewhere after the auto-generated call of the same signature:
PageMethods.set_path('/items.aspx');
This will make it call your page method using the real url instead of the rewritten one.

JsonResult or Json: which to use?

In ASP.NET MVC 3, which is more correct to use: Json() or new JsonResult()? Either returns the same result. Thanks for helping solve an office debate.
Json() is just an extension method that actually returns a JsonResult object behind the scenes (rather than needing to call the constructor directly).
I almost always use the Extension Method myself. This keeps more in line with the other common return types from Action Methods like View(), PartialView(), etc.
I also make sure to create an extension method for any custom ActionResult types that I create. In the end it's a matter of personal preference.
If you a returning a large dataset as a data source for grid or other UI controls via Ajax, sometimes if this dataset is over 1000 records UI controls will not bind because of maximum Json length is not specified.
So instead of
return Json(data),
you can do this: return new JsonResult(Data = data, MaxJsonLength = 50000);

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.

Resources