Ajax GET Parameter to MVC 5 Controller - ajax

I'm wondering why my ajax call to my Controller works when my Parameter is called id and doesn't work when it's called accountNo or accountId.
Ajax
$.ajax({
type: "GET",
dataType: "json",
cache: false,
url: config.url.root + "/DeferredAccount/GetDeferredAccountDetailsByAccount/" + accountNo
});
Controller
public JsonResult GetDeferredAccountDetailsByAccount(int id)
{
var details = _deferredAccountDetailsService.GetDeferredAccountDetailsByAccount(id);
return Json(details, JsonRequestBehavior.AllowGet);
}
In my Controller - if the parameter is int id everything works.
If I change the Controller parameter to, let's say, accountNum, I receive a 500 error stating that my parameter is null.
So, it's literally just the naming of the Parameter for the Controller that dictates the success of my GET request or not. Is it because it's JSON encoded, and I'm not specifying the data model/format in my ajax method?
If an answer exists for this, I apologize as I haven't come across it.

This is because the RouteConfig.cs by default defines the third component of your route as the variable id.
You can get to that controller by specifying the URL
/DeferredAccount/GetDeferredAccountDetailsByAccount/?accountNum=1
Using attribute routing
There is another more fine-grained way of serving your routing with MVC 5 known as attribute routing.
Edit RouteConfig.cs
Add routes.MapMvcAttributeRoutes();
Edit Controller
[Route("/whatever/path/i/like/{accountNum:int}")]
public JsonResult GetDeferredAccountDetailsByAccount(int accountNum)
{
[...]
}
MSDN: Attribute Routing in ASP.NET MVC 5

you may put below Route on top in your RouteConfig.cs file
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "DeferredAccount", action = "GetDeferredAccountDetailsByAccount", id = UrlParameter.Optional }
);

Related

web api support parameters while they don't have one

http://localhost:xxxx/api/BindAppointmentResources
works fine for me but when I'm trying to add any invalid object after controller (with this ? "http://localhost:xxxxx/api/BindAppointmentResources?Userid") in URL its gets the same result
I tried action-based routing , attribute routing so far but same result?
PS : I don't have parameters in WEB API
Route Config :
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
Query string parameters will automatically get bound to your parameters that have the same name in web api.
If no parameter names are found it will route the request to the base url (which is the url before the question mark).
So this url
http://localhost:xxxx/api/BindAppointmentResources?UserID=1
will, if no method with parameter name that match UserID are found, end up being routed to
http://localhost:xxxx/api/BindAppointmentResources
In the Get method you can still get the query string
var queryString = this.Request.GetQueryNameValuePairs();
To prevent binding parameters from query string and only allow bindings from route values, you could remove the default QueryStringValueProviderFactory from the default HttpConfiguration configuration. Read more about it in this article

Need to design a custom route in ASP.NET MVC 3?

I have designed a custom route which looks like below
"\client\{CLIENTCODE}\{Controller}\{View}\{id}"
other than this route I also have default MVC route intact.
The {CLIENTCODE} is 4 character length string in the URL,which will be used to detect a connection string and do operation on respective database.
I am facing two issues
All Ajax request take default route when I use AJAX URL as 'Controller\View'. How can I append {CLIENTCODE} to every AJAX request.
I am loosing {CLIENTCODE} from URL after the session expires and I am unable to get it in Global.ASAX.
If u need append this route to ajax request you need set the ajax url with your route.
$.ajax({
type: "POST",
url: '#Url.RouteUrl("routeName", new { code="code", controller="controller", action="action"})',
dataType: "html",
success: function (data) {
$("#product-attribute-values").append(data);
}
})
And what you mean 'loosing when session expired'? You can acces all route values with code like this in global.asax
protected void Application_BeginRequest()
{
string code = Request.RequestContext.RouteData.Values["code"].ToString();
}

Route from Incoming ASPX url to an ASP.NET MVC Controller Action

I have a url Review.aspx?reviewId=3 and I'd like to have this url be routed to an MVC controller/action Review/3. Any ideas?
Never mind, a simple route like this worked:
routes.MapRoute(
"Reviews_Old", // Route name
"LOreview.aspx", // URL with parameters
new { controller = "LOReview", action = "Review", id = UrlParameter.Optional } // Parameter defaults
);
And the query string parameters are model bound on the controller action parameters

mvc3 IModelBinder and url

I'm having a problem using iModelBinder with url in the format of
http://localhost/controller/action/id/value
the action would be the function in the controller
the id/value is ie. id=12
When I try the above link i receive a 404 error page not found, and looking at the stack I can understand that MVC is looking for a path it does not understand.
using the following works
http://localhost/controller/action?id=value
If anyone as any idea if this problem can be resolved, I would really like to be able to use "/" as separators.
Vince
The url should really be in the format:
http://localhost/controller/action/id
For example:
http://localhost/products/index/1
And the id should then be specified in the controller action. For example:
public ActionResult Index(int id)
{
...
The route specified in the global.asax file will specify the format of the url. For the above url the default route will suffice:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
Then the default model binder will automatically bind your id (i.e. 1 in the above url) to the int id in the action.
Like Adam was suggesting, I don't think you should specify the name of the id in the url as it is automatically bound to for you by the default model binder.

ASP.net MVC RenderAction and Route

I have a web project using ASP.net MVC3. There's an child action in my project. I use
<% Html.RenderAction("Navigator", "Application");%>
to call a shared action. But I find that if my current url is "localhost/application", it throws an exception "No route in the route table matches the supplied values". But when current url is "localhost/application/index", it works fine. Index is a default action in my route config, which is shown below:
public static void RegisterRoutesTo(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
//routes.IgnoreRoute("{*chartName}", new { chartName = #"(.*)?Chart.aspx" }); //ignore request for charting request
routes.Ignore("{*pathInfo}", new { pathInfo = #"^.*(ChartImg.axd)$" });
routes.MapRoute(
"Default", // Route name
"{controller}/{id}/{action}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { httpMethod = new HttpMethodConstraint("GET", "POST") } // Allowed http methods
);
}
Note that I switch default id and action position. I see mvc can remove the default controller and action name in url when using "Html.ActionLink(...)". And I don't like to use explicit url string in my views. How can make it work?
My Action code is simple:
[ChildActionOnly]
public ActionResult Navigator()
{
return PartialView(appFacility.GetAll());
}
Thanks alot.
Wrong route URL definition and defaults combination
The problem is that you can't have non optional parameters after an optional parameter.
Why does localhost/application/index work? This are route values:
controller = "application" (supplied from URL)
id = "index" (supplied from URL)
action = "Index" (supplied as route default)
Basically these values equal to localhost/application/index/index request URL.
If you'd like your RenderAction to work, you'd have to call it this way:
<% Html.RenderAction("Navigator", "Application", new { id = 0 }); %>
which would equal to localhost/application/0/navigator request URL.
But you'll soon find out that your route doesn't work and you'll have to change it (because I suppose you don't like having that additional 0 in your URL). If you provide information how you'd like your route work (or why you've decided to switch action and id) we can provide an answer that will help you meet your requirements.
Optinal parameters work correctly only on the end of route. Try something like this:
routes.MapRoute("DefaultWithID", "{controller}/{id}/{action}",
new { action = "Index" },
new { id = "^[0-9]+$" }
);
routes.MapRoute("Default", "{controller}/{action}",
new { controller = "Home", action = "Index" }
);
edit: hopefully fixed :) this version counts on fact that ID will be numeric - without constraint we can't tell whether it would mean action or id, so there couldn't be default action on routes when ID is specified

Resources