I’m having difficulty with the concept of Routing within the ASP.NET MVC Framework. For example, I have a controller method:
public class UploadController : Controller
{
public ActionResult Index()
{
return View();
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetChildFolders(string id)
{
IEnumerable<MyModel> list = MyModelDataContext.GetChildFolders( new Guid(id) );
IEnumerable<SelectListItem> listitems = list.Select(row => new SelectListItem
{
Value = row.FolderID.ToString(),
Text = row.FolderName
});
return this.Json(listitems, JsonRequestBehavior.AllowGet);
}
}
and here’s my route:
routes.MapRoute(
"UploadRoute", // Route name
"Upload/{id}", // URL with parameters
new { controller = "Upload", action = "Index", id = UrlParameter.Optional
});
Now, if I have two jQuery functions:
function TeamChange1() {
var id = $('#TeamList').val();
$.getJSON('/Upload/GetChildFolders/' + id, null, function(data) {
bindOptionResults(data);
});
}
function TeamChange2() {
var id = $('#TeamList').val();
$.getJSON('/Upload/GetChildFolders', id, function(data) {
bindOptionResults(data);
});
}
TeamChange1() will call the GetChildFolders() method with the id parameter properly wired up and filled in, however, with TeamChange2() the id parameter remains null in the controller method. This must be a routing issue that causes this. What is the explaination?
You don’t actually need routing here. In fact the default route
{controller}\{action}\{id}matches your controller, action, and parameter name (id) already so definingUploadRouteis redundant.The reason TeamChange2() doesn’t work is because
idis a string, not an object. The proper code is:This will pass
idin the params collection instead of the url. MVC doesn’t care and will still bind since the parameter name matches theidroute parameter. Watch the requests in FireBug to see the difference.Also, you can change your
idparameter in the controller action to the Guid data type so you don’t have to donew Guid(id)in the code.