Search Results

Search found 202 results on 9 pages for 'maproute'.

Page 5/9 | < Previous Page | 1 2 3 4 5 6 7 8 9  | Next Page >

  • Need Help With ASP.NET Custom Route

    - by Jason
    I need to create a custom route to list all the rooms in a given building. So, I want the url to look something like this: /Building/1000/Room Which would list all the rooms in Building 1000. Is this the correct mapping for the route (to call the IndexByBuilding method in RoomController)? routes.MapRoute( "RoomsByBuilding", "Building/{id}/Room", new { controller = "Room", action = "IndexByBuilding", id = "" } );

    Read the article

  • Routing optional parameters with dashes in MVC

    - by Géza
    I've made an routing definition like this: routes.MapRoute("ProductSearch", "Search-{MainGroup}-{SubGroup}-{ItemType}", new { controller = "Product", action = "Search", MainGroup = "", SubGroup = "", ItemWebType = ""}); It is not working if the parameters are empty. Actually it resolves the url, so Url.Action method resolves the path "Search-12--" but the link is not working, so the GET of the page is not working With slashes it is working the Url.Action method makes "Search/12" "Search/{MainGroup}/{SubGroup}/{ItemType}" is it somehow possible to correct it?

    Read the article

  • rewrite routes for URl

    - by user348173
    I have the following URl: http://localhost:12981/BaseEvent/EventOverview/12?type=Film This is route: routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); I want that in a browser the url looks like: http://localhost:12981/Film/Overview/12 How can I do this? One more example: http://localhost:12981/BaseEvent/EventOverview/15?type=Sport should be http://localhost:12981/Sport/Overview/15 Thanks.

    Read the article

  • how to have minimum AreaRegistrations with putting duplicated elements in single place

    - by Sadegh
    hi all, i have several AreaRegistration classes which one each registers own routes and each one have some duplicated elements such as bolded text in below: context.MapRoute("Search", "**{culture}/{style}**/search", new { **culture = cultureValue, style = styleValue,** controller = "search", action = "default" }, new { **culture = new CultureRouteConstraint(), style = new StyleRouteConstraint()** }); how i can have minimum AreaRegistrations with putting duplicated elements in single place which handles that? this is possible?

    Read the article

  • Custom route does not work in ASP.net MVC 3

    - by user603007
    I am trying to implement my custom route in ASP.net MVC 3 but I get this error: The resource cannot be found. global.asax public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "mycontroller", // Route name "{controller}/{name}", // URL with parameters new { controller = "MyController", action = "Search" } // Parameter defaults ); } MyController.cs public class MyController : Controller { public ActionResult Search(string name) { return Content(name); } }

    Read the article

  • MvcExtensions – Bootstrapping

    - by kazimanzurrashid
    When you create a new ASP.NET MVC application you will find that the global.asax contains the following lines: namespace MvcApplication1 { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } } } As the application grows, there are quite a lot of plumbing code gets into the global.asax which quickly becomes a design smell. Lets take a quick look at the code of one of the open source project that I recently visited: public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute("Default","{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" }); } protected override void OnApplicationStarted() { Error += OnError; EndRequest += OnEndRequest; var settings = new SparkSettings() .AddNamespace("System") .AddNamespace("System.Collections.Generic") .AddNamespace("System.Web.Mvc") .AddNamespace("System.Web.Mvc.Html") .AddNamespace("MvcContrib.FluentHtml") .AddNamespace("********") .AddNamespace("********.Web") .SetPageBaseType("ApplicationViewPage") .SetAutomaticEncoding(true); #if DEBUG settings.SetDebug(true); #endif var viewFactory = new SparkViewFactory(settings); ViewEngines.Engines.Add(viewFactory); #if !DEBUG PrecompileViews(viewFactory); #endif RegisterAllControllersIn("********.Web"); log4net.Config.XmlConfigurator.Configure(); RegisterRoutes(RouteTable.Routes); Factory.Load(new Components.WebDependencies()); ModelBinders.Binders.DefaultBinder = new Binders.GenericBinderResolver(Factory.TryGet<IModelBinder>); ValidatorConfiguration.Initialize("********"); HtmlValidationExtensions.Initialize(ValidatorConfiguration.Rules); } private void OnEndRequest(object sender, System.EventArgs e) { if (((HttpApplication)sender).Context.Handler is MvcHandler) { CreateKernel().Get<ISessionSource>().Close(); } } private void OnError(object sender, System.EventArgs e) { CreateKernel().Get<ISessionSource>().Close(); } protected override IKernel CreateKernel() { return Factory.Kernel; } private static void PrecompileViews(SparkViewFactory viewFactory) { var batch = new SparkBatchDescriptor(); batch.For<HomeController>().For<ManageController>(); viewFactory.Precompile(batch); } As you can see there are quite a few of things going on in the above code, Registering the ViewEngine, Compiling the Views, Registering the Routes/Controllers/Model Binders, Settings up Logger, Validations and as you can imagine the more it becomes complex the more things will get added in the application start. One of the goal of the MVCExtensions is to reduce the above design smell. Instead of writing all the plumbing code in the application start, it contains BootstrapperTask to register individual services. Out of the box, it contains BootstrapperTask to register Controllers, Controller Factory, Action Invoker, Action Filters, Model Binders, Model Metadata/Validation Providers, ValueProvideraFactory, ViewEngines etc and it is intelligent enough to automatically detect the above types and register into the ASP.NET MVC Framework. Other than the built-in tasks you can create your own custom task which will be automatically executed when the application starts. When the BootstrapperTasks are in action you will find the global.asax pretty much clean like the following: public class MvcApplication : UnityMvcApplication { public void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e) { Check.Argument.IsNotNull(e, "e"); HttpException exception = e.Exception.GetBaseException() as HttpException; if ((exception != null) && (exception.GetHttpCode() == (int)HttpStatusCode.NotFound)) { e.Dismiss(); } } } The above code is taken from my another open source project Shrinkr, as you can see the global.asax is longer cluttered with any plumbing code. One special thing you have noticed that it is inherited from the UnityMvcApplication rather than regular HttpApplication. There are separate version of this class for each IoC Container like NinjectMvcApplication, StructureMapMvcApplication etc. Other than executing the built-in tasks, the Shrinkr also has few custom tasks which gets executed when the application starts. For example, when the application starts, we want to ensure that the default users (which is specified in the web.config) are created. The following is the custom task that is used to create those default users: public class CreateDefaultUsers : BootstrapperTask { protected override TaskContinuation ExecuteCore(IServiceLocator serviceLocator) { IUserRepository userRepository = serviceLocator.GetInstance<IUserRepository>(); IUnitOfWork unitOfWork = serviceLocator.GetInstance<IUnitOfWork>(); IEnumerable<User> users = serviceLocator.GetInstance<Settings>().DefaultUsers; bool shouldCommit = false; foreach (User user in users) { if (userRepository.GetByName(user.Name) == null) { user.AllowApiAccess(ApiSetting.InfiniteLimit); userRepository.Add(user); shouldCommit = true; } } if (shouldCommit) { unitOfWork.Commit(); } return TaskContinuation.Continue; } } There are several other Tasks in the Shrinkr that we are also using which you will find in that project. To create a custom bootstrapping task you have create a new class which either implements the IBootstrapperTask interface or inherits from the abstract BootstrapperTask class, I would recommend to start with the BootstrapperTask as it already has the required code that you have to write in case if you choose the IBootstrapperTask interface. As you can see in the above code we are overriding the ExecuteCore to create the default users, the MVCExtensions is responsible for populating the  ServiceLocator prior calling this method and in this method we are using the service locator to get the dependencies that are required to create the users (I will cover the custom dependencies registration in the next post). Once the users are created, we are returning a special enum, TaskContinuation as the return value, the TaskContinuation can have three values Continue (default), Skip and Break. The reason behind of having this enum is, in some  special cases you might want to skip the next task in the chain or break the complete chain depending upon the currently running task, in those cases you will use the other two values instead of the Continue. The last thing I want to cover in the bootstrapping task is the Order. By default all the built-in tasks as well as newly created task order is set to the DefaultOrder(a static property), in some special cases you might want to execute it before/after all the other tasks, in those cases you will assign the Order in the Task constructor. For Example, in Shrinkr, we want to run few background services when the all the tasks are executed, so we assigned the order as DefaultOrder + 1. Here is the code of that Task: public class ConfigureBackgroundServices : BootstrapperTask { private IEnumerable<IBackgroundService> backgroundServices; public ConfigureBackgroundServices() { Order = DefaultOrder + 1; } protected override TaskContinuation ExecuteCore(IServiceLocator serviceLocator) { backgroundServices = serviceLocator.GetAllInstances<IBackgroundService>().ToList(); backgroundServices.Each(service => service.Start()); return TaskContinuation.Continue; } protected override void DisposeCore() { backgroundServices.Each(service => service.Stop()); } } That’s it for today, in the next post I will cover the custom service registration, so stay tuned.

    Read the article

  • Routing Issue in ASP.NET MVC 3 RC 2

    - by imran_ku07
         Introduction:             Two weeks ago, ASP.NET MVC team shipped the ASP.NET MVC 3 RC 2 release. This release includes some new features and some performance optimization. This release also fixes most of the bugs but still some minor issues are present in this release. Some of these issues are already discussed by Scott Guthrie at Update on ASP.NET MVC 3 RC2 (and a workaround for a bug in it). In addition to these issues, I have found another issue in this release regarding routing. In this article, I will show you the issue regarding routing and a simple workaround for this issue.       Description:             The easiest way to understand an issue is to reproduce it in the application. So create a MVC 2 application and a MVC 3 RC 2 application. Then in both applications, just open global.asax file and update the default route as below,     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id1}/{id2}", // URL with parameters new { controller = "Home", action = "Index", id1 = UrlParameter.Optional, id2 = UrlParameter.Optional } // Parameter defaults );              Then just open Index View and add the following lines,    <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Home Page </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <% Html.RenderAction("About"); %> </asp:Content>             The above view will issue a child request to About action method. Now run both applications. ASP.NET MVC 2 application will run just fine. But ASP.NET MVC 3 RC 2 application will throw an exception as shown below,                  You may think that this is a routing issue but this is not the case here as both ASP.NET MVC 2 and ASP.NET MVC  3 RC 2 applications(created above) are built with .NET Framework 4.0 and both will use the same routing defined in System.Web. Something is wrong in ASP.NET MVC 3 RC 2. So after digging into ASP.NET MVC source code, I have found that the UrlParameter class in ASP.NET MVC 3 RC 2 overrides the ToString method which simply return an empty string.     public sealed class UrlParameter { public static readonly UrlParameter Optional = new UrlParameter(); private UrlParameter() { } public override string ToString() { return string.Empty; } }             In MVC 2 the ToString method was not overridden. So to quickly fix the above problem just replace UrlParameter.Optional default value with a different value other than null or empty(for example, a single white space) or replace UrlParameter.Optional default value with a new class object containing the same code as UrlParameter class have except the ToString method is not overridden (or with a overridden ToString method that return a string value other than null or empty). But by doing this you will loose the benefit of ASP.NET MVC 2 Optional URL Parameters. There may be many different ways to fix the above problem and not loose the benefit of optional parameters. Here I will create a new class MyUrlParameter with the same code as UrlParameter class have except the ToString method is not overridden. Then I will create a base controller class which contains a constructor to remove all MyUrlParameter route data parameters, same like ASP.NET MVC doing with UrlParameter route data parameters early in the request.     public class BaseController : Controller { public BaseController() { if (System.Web.HttpContext.Current.CurrentHandler is MvcHandler) { RouteValueDictionary rvd = ((MvcHandler)System.Web.HttpContext.Current.CurrentHandler).RequestContext.RouteData.Values; string[] matchingKeys = (from entry in rvd where entry.Value == MyUrlParameter.Optional select entry.Key).ToArray(); foreach (string key in matchingKeys) { rvd.Remove(key); } } } } public class HomeController : BaseController { public ActionResult Index(string id1) { ViewBag.Message = "Welcome to ASP.NET MVC!"; return View(); } public ActionResult About() { return Content("Child Request Contents"); } }     public sealed class MyUrlParameter { public static readonly MyUrlParameter Optional = new MyUrlParameter(); private MyUrlParameter() { } }     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id1}/{id2}", // URL with parameters new { controller = "Home", action = "Index", id1 = MyUrlParameter.Optional, id2 = MyUrlParameter.Optional } // Parameter defaults );             MyUrlParameter class is a copy of UrlParameter class except that MyUrlParameter class not overrides the ToString method. Note that the default route is modified to use MyUrlParameter.Optional instead of UrlParameter.Optional. Also note that BaseController class constructor is removing MyUrlParameter parameters from the current request route data so that the model binder will not bind these parameters with action method parameters. Now just run the ASP.NET MVC 3 RC 2 application again, you will find that it runs just fine.             In case if you are curious to know that why ASP.NET MVC 3 RC 2 application throws an exception if UrlParameter class contains a ToString method which returns an empty string, then you need to know something about a feature of routing for url generation. During url generation, routing will call the ParsedRoute.Bind method internally. This method includes a logic to match the route and build the url. During building the url, ParsedRoute.Bind method will call the ToString method of the route values(in our case this will call the UrlParameter.ToString method) and then append the returned value into url. This method includes a logic after appending the returned value into url that if two continuous returned values are empty then don't match the current route otherwise an incorrect url will be generated. Here is the snippet from ParsedRoute.Bind method which will prove this statement.       if ((builder2.Length > 0) && (builder2[builder2.Length - 1] == '/')) { return null; } builder2.Append("/"); ........................................................... ........................................................... ........................................................... ........................................................... if (RoutePartsEqual(obj3, obj4)) { builder2.Append(UrlEncode(Convert.ToString(obj3, CultureInfo.InvariantCulture))); continue; }             In the above example, both id1 and id2 parameters default values are set to UrlParameter object and UrlParameter class include a ToString method that returns an empty string. That's why this route will not matched.            Summary:             In this article I showed you the issue regarding routing and also showed you how to workaround this problem. I explained this issue with an example by creating a ASP.NET MVC 2 and a ASP.NET MVC 3 RC 2 application. Finally I also explained the reason for this issue. Hopefully you will enjoy this article too.   SyntaxHighlighter.all()

    Read the article

  • IIS is overriding my response content, if i manually set the Response.StatusCode

    - by Pure.Krome
    Hi Folks, Problem when i manually set the HTTP Status of my Response stream to .. say 404 or 503, IIS renders up the stock IIS content/view, instead of my custom view. When I do this with the Web Development Server (aka. Casinni), it works correctly (ie. my content is displayed and the response.statuscode == my entered data. Is there anyway I can override this behaviour? How To Replicate Make a default ASP.NET MVC1 web app. Add the following route public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", "{*catchall}", new { controller = "Home", action = "Index" } ); } Now replace the the HomeController's Index method with... [HandleError] public class HomeController : Controller { public ActionResult Index() { Response.StatusCode = 404; return View(); } } :( Please help!

    Read the article

  • How to work RavenDB Id with ASP.NET MVC Routes

    - by shiju
    By default RavenDB's Id would be sperated by "/". Let's say that we have a category object, the Ids would be like "categories/1". This will make problems when working with ASP.NET MVC's route rule. For a route category/edit/id, the uri would be category/edit/categories/1. You can solve this problem in two waysSolution 1 - Change Id SeparatorWe can use different Id Separator for RavenDB Ids in order to working with ASP.NET MVC route rules. The following code specify that Ids would be seperated by "-" rather than the default "/"  documentStore = new DocumentStore { Url = "http://localhost:8080/" };  documentStore.Initialize();  documentStore.Conventions.IdentityPartsSeparator = "-"; The above IdentityPartsSeparator would be generate Ids like "categories-1"Solution 2 - Modify ASP.NET MVC Route Modify the ASP.NET MVC routes in the Global.asax.cs file, as shown in the following code  routes.MapRoute(     "WithParam",                                           // Route name     "{controller}/{action}/{*id}"                         // URL with parameters     );  We just put "*" in front of the id variable that will be working with the default Id separator of RavenDB

    Read the article

  • Fixing Chrome&rsquo;s AJAX Request Caching Bug

    - by Steve Wilkes
    I recently had to make a set of web pages restore their state when the user arrived on them after clicking the browser’s back button. The pages in question had various content loaded in response to user actions, which meant I had to manually get them back into a valid state after the page loaded. I got hold of the page’s data in a JavaScript ViewModel using a JQuery ajax call, then iterated over the properties, filling in the fields as I went. I built in the ability to describe dependencies between inputs to make sure fields were filled in in the correct order and at the correct time, and that all worked nicely. To make sure the browser didn’t cache the AJAX call results I used the JQuery’s cache: false option, and ASP.NET MVC’s OutputCache attribute for good measure. That all worked perfectly… except in Chrome. Chrome insisted on retrieving the data from its cache. cache: false adds a random query string parameter to make the browser think it’s a unique request – it made no difference. I made the AJAX call a POST – it made no difference. Eventually what I had to do was add a random token to the URL (not the query string) and use MVC routing to deliver the request to the correct action. The project had a single Controller for all AJAX requests, so this route: routes.MapRoute( name: "NonCachedAjaxActions", url: "AjaxCalls/{cacheDisablingToken}/{action}", defaults: new { controller = "AjaxCalls" }, constraints: new { cacheDisablingToken = "[0-9]+" }); …and this amendment to the ajax call: function loadPageData(url) { // Insert a timestamp before the URL's action segment: var indexOfFinalUrlSeparator = url.lastIndexOf("/"); var uniqueUrl = url.substring(0, indexOfFinalUrlSeparator) + new Date().getTime() + "/" + url.substring(indexOfFinalUrlSeparator); // Call the now-unique action URL: $.ajax(uniqueUrl, { cache: false, success: completePageDataLoad }); } …did the trick.

    Read the article

  • Ninject 2 and MVC 2.0

    - by theouteredge
    I've updated a project to VS2010 and MVC2 from VS2008 and MVC1. I'm having problems with Ninject not finding controllers within Areas Here is my global.asax.cs file: namespace Website { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : NinjectHttpApplication { public static StandardKernel NinjectKernel; public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Balance", "Balance/{action}/{month}/{year}", new { controller = "Balance", action = "Index", month = DateTime.Now.Month, year = DateTime.Now.Year } ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Login", action = "Index", id = "" } // Parameter defaults ); } /* protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); // initializes the NHProfiler so you can see what is going on with your queries HibernatingRhinos.Profiler.Appender.NHibernate.NHibernateProfiler.Initialize(); } */ protected override void OnApplicationStarted() { RegisterRoutes(RouteTable.Routes); AreaRegistration.RegisterAllAreas(); RegisterAllControllersIn(Assembly.GetExecutingAssembly()); } protected void Application_Error(object sender, EventArgs e) { var errorService = NinjectKernel.Get<IErrorLogService>(); errorService.LogError(HttpContext.Current.Server.GetLastError().GetBaseException(), "AppSite"); } protected override IKernel CreateKernel() { if (NinjectKernel == null) { NinjectKernel = new StandardKernel(new ServiceModule()); } return NinjectKernel; } } public class ServiceModule : NinjectModule { public override void Load() { Bind<IHelper>().To<Helper>().InRequestScope(); Bind<IErrorLogService>().To<ErrorLogService>(); Bind<INHSessionFactory>().To<NHSessionFactory>().InSingletonScope(); Bind<ISessionFactory>().ToMethod(ctx => ctx.Kernel.Get<INHSessionFactory>().GetSessionFactory()) .InSingletonScope(); Bind<INHSession>().To<NHSession>(); Bind<ISession>().ToMethod(ctx => ctx.Kernel.Get<INHSession>().GetSession()); } } } Accessing controllers within the /Controllers folder works OK, but accessing controllers within a /Areas/Member/Controller throws the following error: Server Error in '/' Application. Cannot be null Parameter name: service Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.ArgumentNullException: Cannot be null Parameter name: service Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [ArgumentNullException: Cannot be null Parameter name: service] Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot root, Type service, Func`2 constraint, IEnumerable`1 parameters, Boolean isOptional, Boolean isUnique) +193 Ninject.Web.Mvc.NinjectControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +41 System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +66 System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +124 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8771488 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 Version Information: Microsoft .NET Framework Version:4.0.30128; ASP.NET Version:4.0.30128.1 The Url for this request is /Member/Controller/, If I change the Url too /Controller the controller fires but I get an error that the system cannot find the View in the path /Views When it should be looking in /Area/Members/Views I have either done something wrong in the upgrade or I'm missing something bt I just can't figure out what. I've been trying to figure this out for 3 days...

    Read the article

  • Post calls RedirectToAction but view specified in RedirectToAction is not rendered

    - by W4IK
    Here's some of the html <form id="frmSubmit" action="/Viewer" style="display:none;"> <div id="renderSubmit" class="renderReport"> <input type="hidden" name="reportYear" id="reportYear" value="" /> <input type="hidden" name="reportMonth" id="reportMonth" value="" /> <input type="hidden" name="propIds" id="propIds" value="" /> <input type="hidden" name="reportName" id="reportName" value="" /> <input type="hidden" name="reportYearFrom" id="reportYearFrom" value="" /> <input type="hidden" name="reportMonthFrom" id="reportMonthFrom" value="" /> <input type="hidden" name="reportYearTo" id="reportYearTo" value="" /> <input type="hidden" name="reportMonthTo" id="reportMonthTo" value="" /> </div> </form> a little further down the page <div id="reportList" class="renderReport"> <fieldset style="width:105%;"> <legend class="reportStepLegend">Step 3. <br /> Click a report name below to view a report</legend> <br /> <% foreach (ReportMetaData item in (ReportMetaDataContainer)ViewData.Model) { %> <div> <input id=<%=item.SSRSName%> type="button" class="reportLink" value="<%=item.DisplayName%>" /> </div> <%}%> </fieldset> </div> Here's the javascript that gets called when the button is clicked $('.reportLink').click(function() { if (CheckDateAndProps() === true) { $('#reportName').val(this.id); var formData = $("#frmSubmit").serializeArray(); $.post('Home/PostViewer/', formData); } }); Note...i did have the $.post like so earlier...but it didn't seem to make any difference $.post('Home/PostViewer/', formData, function(data) { alert(data.Result); }, "json"); Here's the controller code [AcceptVerbs(HttpVerbs.Post)] public ActionResult PostViewer(string reportYear, string reportMonth, string propIds, string reportName, string reportYearFrom, string reportMonthFrom, string reportYearTo, string reportMonthTo) { return RedirectToAction("Viewer"); } All is good in the world up to this point..I'm hitting the above method and all the values are populated. Here's the get ActionResult method [AcceptVerbs(HttpVerbs.Get)] public ActionResult Viewer(string reportYear, string reportMonth, string propIds, string reportName, string reportYearFrom, string reportMonthFrom, string reportYearTo, string reportMonthTo) { return View(); } I'm hitting this too...not seeing any values in the parameters...but that's just because I haven't passed them in yet...I don't think that's whats keeping the Viewer page from displaying.? Now...one would one expect the Viewer view to be rendered...right?...well all I see is the page that this was called from...it never displays the Viewer page???!!?!? Here's the routes from global.asax routes.MapRoute( "Viewer", // Route name "Home/Viewer", // URL with parameters new { controller = "Home", action = "Viewer" } // Parameter defaults ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); I can browse directly to the page http://localhost:50083/Home/Viewer and when I do so I hit the get ActionResult method and the page renders just fine. Any help is greatly appreciated!

    Read the article

  • MVC SiteMap - when different nodes point to same action SiteMap.CurrentNode does not map to the correct route

    - by awrigley
    Setup: I am using ASP.NET MVC 4, with mvcSiteMapProvider to manage my menus. I have a custom menu builder that evaluates whether a node is on the current branch (ie, if the SiteMap.CurrentNode is either the CurrentNode or the CurrentNode is nested under it). The code is included below, but essentially checks the url of each node and compares it with the url of the currentnode, up through the currentnodes "family tree". The CurrentBranch is used by my custom menu builder to add a class that highlights menu items on the CurrentBranch. The Problem: My custom menu works fine, but I have found that the mvcSiteMapProvider does not seem to evaluate the url of the CurrentNode in a consistent manner: When two nodes point to the same action and are distinguished only by a parameter of the action, SiteMap.CurrentNode does not seem to use the correct route (it ignores the distinguishing parameter and defaults to the first route that that maps to the action defined in the node). Example of the Problem: In an app I have Members. A Member has a MemberStatus field that can be "Unprocessed", "Active" or "Inactive". To change the MemberStatus, I have a ProcessMemberController in an Area called Admin. The processing is done using the Process action on the ProcessMemberController. My mvcSiteMap has two nodes that BOTH map to the Process action. The only difference between them is the alternate parameter (such are my client's domain semantics), that in one case has a value of "Processed" and in the other "Unprocessed": Nodes: <mvcSiteMapNode title="Process" area="Admin" controller="ProcessMembers" action="Process" alternate="Unprocessed" /> <mvcSiteMapNode title="Change Status" area="Admin" controller="ProcessMembers" action="Process" alternate="Processed" /> Routes: The corresponding routes to these two nodes are (again, the only thing that distinguishes them is the value of the alternate parameter): context.MapRoute( "Process_New_Members", "Admin/Unprocessed/Process/{MemberId}", new { controller = "ProcessMembers", action = "Process", alternate="Unprocessed", MemberId = UrlParameter.Optional } ); context.MapRoute( "Change_Status_Old_Members", "Admin/Members/Status/Change/{MemberId}", new { controller = "ProcessMembers", action = "Process", alternate="Processed", MemberId = UrlParameter.Optional } ); What works: The Html.ActionLink helper uses the routes and produces the urls I expect: @Html.ActionLink("Process", MVC.Admin.ProcessMembers.Process(item.MemberId, "Unprocessed") // Output (alternate="Unprocessed" and item.MemberId = 12): Admin/Unprocessed/Process/12 @Html.ActionLink("Status", MVC.Admin.ProcessMembers.Process(item.MemberId, "Processed") // Output (alternate="Processed" and item.MemberId = 23): Admin/Members/Status/Change/23 In both cases the output is correct and as I expect. What doesn't work: Let's say my request involves the second option, ie, /Admin/Members/Status/Change/47, corresponding to alternate = "Processed" and a MemberId of 47. Debugging my static CurrentBranch property (see below), I find that SiteMap.CurrentNode shows: PreviousSibling: null Provider: {MvcSiteMapProvider.DefaultSiteMapProvider} ReadOnly: false ResourceKey: "" Roles: Count = 0 RootNode: {Home} Title: "Process" Url: "/Admin/Unprocessed/Process/47" Ie, for a request url of /Admin/Members/Status/Change/47, SiteMap.CurrentNode.Url evaluates to /Admin/Unprocessed/Process/47. Ie, it is ignorning the alternate parameter and using the wrong route. CurrentBranch Static Property: /// <summary> /// ReadOnly. Gets the Branch of the Site Map that holds the SiteMap.CurrentNode /// </summary> public static List<SiteMapNode> CurrentBranch { get { List<SiteMapNode> currentBranch = null; if (currentBranch == null) { SiteMapNode cn = SiteMap.CurrentNode; SiteMapNode n = cn; List<SiteMapNode> ln = new List<SiteMapNode>(); if (cn != null) { while (n != null && n.Url != SiteMap.RootNode.Url) { // I don't need to check for n.ParentNode == null // because cn != null && n != SiteMap.RootNode ln.Add(n); n = n.ParentNode; } // the while loop excludes the root node, so add it here // I could add n, that should now be equal to SiteMap.RootNode, but this is clearer ln.Add(SiteMap.RootNode); // The nodes were added in reverse order, from the CurrentNode up, so reverse them. ln.Reverse(); } currentBranch = ln; } return currentBranch; } } The Question: What am I doing wrong? The routes are interpreted by Html.ActionLlink as I expect, but are not evaluated by SiteMap.CurrentNode as I expect. In other words, in evaluating my routes, SiteMap.CurrentNode ignores the distinguishing alternate parameter.

    Read the article

  • ASP.NET MVC Html.BeginRouteForm render's action with problem

    - by Sadegh
    hi, i defined this route: context.MapRoute("SearchEngineWebSearch", "{culture}/{style}/search/web/{query}/{index}/{size}", new { controller = "search", action = "web", query = "", index = 0, size = 5 }, new { index = new UInt32RouteConstraint(), size = new UInt32RouteConstraint() }); and form to post parameter to that: <% using (Html.BeginRouteForm("SearchEngineWebSearch", FormMethod.Post)) { %> <input name="query" type="text" value="<%: ViewData["Query"]%>" class="search-field" /> <input type="submit" value="Search" class="search-button" /> <%} %> but form rendered with problem. why? thanks in advance ;)

    Read the article

  • RouteTable.Routes.GetVirtualPath with route data asp.net MVC 2

    - by Bill
    Dear all, I'm trying to get a URL from my routes table. Here is the method. private static void RedirectToRoute(ActionExecutingContext context, string param) { var actionName = context.ActionDescriptor.ActionName; var controllerName = context.ActionDescriptor.ControllerDescriptor.ControllerName; var rc = new RequestContext(context.HttpContext, context.RouteData); string url = RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { actionName = actionName, controller = controllerName, parameter = param })).VirtualPath; context.HttpContext.Response.Redirect(url, true); } I'm trying to map it to. However RouteTable.Routes.GetVirtualPath(rc, new RouteValueDictionary(new { actionName = actionName, controller = controllerName, parameter = param })) keeps giving me null. Any thoughts? routes.MapRoute( "default3", // Route name "{parameter}/{controller}/{action}", // URL with parameters new { parameter= "parameterValue", controller = "Home", action = "Index" } ); I know I can use redirectToAction and other methods, but I would like to change the URL in the browser with new routedata.

    Read the article

  • Spark-View-Engine with ASP.NET MVC2

    - by Ben
    How do you modify a ASP.NET MVC 2.0 project to work with the Spark View Engine? I tried like described here: http://dotnetslackers.com/articles/aspnet/installing-the-spark-view-engine-into-asp-net-mvc-2-preview-2.aspx But somehow it still tries to route to .aspx files. Here the code of my global.asax: public class MvcApplication : System.Web.HttpApplication { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); } protected void Application_Start() { SparkViewFactory svf = new SparkViewFactory(); PrecompileViews(svf); AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } public static void PrecompileViews(SparkViewFactory svf) { var controllerFactory = svf; var viewFactory = new SparkViewFactory(controllerFactory.Settings); var batch = new SparkBatchDescriptor(); batch .For<HomeController>() .For<AccountController>(); viewFactory.Precompile(batch); } } }

    Read the article

  • ASP.NET MVC Pass mutiple params from getJson to controller

    - by andyJ
    Hi, I am making a call to a controller action in javascript using the getJson method. I need to pass two parameters to my action method on the controller, but I am struggling to do so. I do not fully understand the routing tables and not sure if this is what I need to use to get this working. Please see example below of what I am trying to do. var action = "<%=Url.Content('~/Postcode/GetAddressResults/')%>" + $get("Premise").value + "/" + $get("SearchPostcode").value $.getJSON(action, null, function(data) { $("#AddressDropDown").fillSelect(data); }); This is my route which I don't understand how to make use of... routes.MapRoute( "postcode", "Postcode/GetAddressResults/{premise}/{postcode}", new { controller = "Motor", action = "GetAddressResults", premise = "", postcode = "" });

    Read the article

  • The parameters dictionary contains a null entry for parameter 'productId' of non-nullable type 'Syst

    - by Naim
    Hi Guys, I am trying to implement an edit page in order administrator to modify data in database.Unfortunately I am encountering an error. The code below: public ViewResult Edit(int productId) { // Do something here } but I am getting this error: "The parameters dictionary contains a null entry for parameter 'productId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ViewResult Edit(Int32)' in 'WebUI.Controllers.AdminController'. To make a parameter optional its type should be either a reference type or a Nullable type. Parameter name: parameters" I changed my route in Global.asax.cs like this: routes.MapRoute( "Admin", "Admin/{action}/{ productId}", new { controller = "Admin", action = "Edit", productId= "" } ); but still I am getting the error Thanks for your help! Naim

    Read the article

  • remove dead routes in asp.net mvc 2

    - by loviji
    hello, i have get a problem. The request for 'Account' has found the following matching controllers: uqs.Controllers.Admin.AccountController MvcApplication1.Controllers.AccountController I search in project by Visual Studio MvcApplication1.Controllers.AccountController to remove it. but can't find match. So, I try to register a route: routes.MapRoute( "LogAccount", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "AccountController", action = "LogOn", id = "" }, new string[] { "uqs.Controllers.Admin" } // Parameter defaults ); But can't solve problem. Multiple types were found that match the controller named 'Account'. How I can Remove MvcApplication1.Controllers.AccountController. or fix this problem? Thanks.

    Read the article

  • ASP.NET MVC POST Parameter into RouteData

    - by David Thomas Garcia
    I'm using jQuery to POST an Id to my route, for example: http://localhost:1234/Load/Delete with a POST Parameter Id = 1 I'm only using the default route in Global.asax.cs right now: routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); When I perform the POST, in my ActionFilter filterContext.RouteData.Values["Id"] is set to the default value of "". Ideally, I'd like it to use the POST Parameter value automatically if the URL comes up with "". I know it is posting properly because I can see the value of "1" in filterContext.HttpContext.Request.Params["Id"]. Is there a way to get RouteData to use a POST parameter as a fall back value?

    Read the article

  • Trouble setting a default controller in MVC 2 RC Area

    - by mannish
    This should be simple, but alas... I've set up an Admin area within my MVC 2 project (single project areas). I've created a couple controllers and their respective view folders. In the AreaRegistration.RegisterArea method, I've specified that I want the default controller to be "Dashboard": public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Admin_default", "Admin/{controller}/{action}/{id}", new { controller = "Dashboard", action = "Index", id = "" }, new string[] { "Admin" } ); } If I navigate to url/Admin/Dashboard, the index comes up just fine. What I want, though, is to allow the user to go to url/Admin/ and see the same thing. When I do this, however, I get "The resource cannot be found". I'm just getting my feet wet with MVC 2's Area implementation, and I don't think I'm doing anything overly complicated... Anyone had the same problem? Do I need to specify a separate route, perhaps at the root, non-area level?

    Read the article

  • Different controllers with the same name in two different areas results in a routing conflict

    - by HackedByChinese
    I have two areas: ControlPanel and Patients. Both have a controller called ProblemsController that are similar in name only. The desired results would be routes that yield /controlpanel/problems = MyApp.Areas.ControlPanel.Controllers.ProblemsController and /patients/problems = MyApp.Areas.Patients.Controllers.ProblemsController. Each has routes configured like this: public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "**Area Name Here**_default", "**Area Name Here**/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); } where **Area Name Here** is either ControlPanel or Patients. When I go to /patients/problems/create (for example), I get a 404 where the routing error says: A public action method 'create' was not found on controller 'MyApp.Areas.ControlPanel.Controllers.ProblemsController'. I'm not sure what I'm doing wrong.

    Read the article

  • How can I make this Route (ASP.Net MVC2) ?

    - by Felipe
    Hi All, I'm begginer in asp.net mvc and I have some doutbs about routes. Im' developing a system to manage documents and I need make an URL like this: routes.MapRoute("Documentos", "{controller}/{documentType}/{documento}/{action}/{id}", new { controller = "Home", documentType = "", documento = "", action = "Index", id = UrlParameter.Optional }); and the app working an URL like theses: "Document/Administrative/Contract" - (Index action by default to list documents of type 'Contract') "Document/Administrative/Contract/New" - (new action in controller) "Document/Administrative/Contract/10" - (detail action in controller) "Document/Administrative/Contract/Edit/10" - (edit action in controller) Document would be a Controller, and Administrative would be just a description in url to identify that documents of 'Contract' is Administrative... So, My doubts is about my controllers and actions, How should be the signature of the methods of controller ? Need I make an Area called Documents to do this more easy ? PS: Sorry for my english! Thanks a lot, Cheers! Felipe

    Read the article

  • ASP.NET MVC Route Contraints with {ID}-{Slug} Format

    - by TimLeung
    I have a route like following, ideally I would like it to match: domain.com/layout/1-slug-is-the-name-of-the-page routes.MapRoute( "Layout", // Route name "layout/{id}-{slug}", // URL with parameters new { controller = "Home", action = "Index", id = @"\d+$" } ); But when I hit the url, I am keep on getting this exception: The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in .... The above route will match the following though: domain.com/layout/1-slug or domain.com/layout/1-slug_permalink Seems like the hyphen that separates the ID from the Slug is causing issues.

    Read the article

  • Ajax call with jQuery in ASP.NET MVC does not pass parameters

    - by desmati
    The Route is: routes.MapRoute( "Ajax", // Route name "BizTalk/Services/{action}", // URL with parameters new { // Parameter defaults controller = "BizTalk" } ); My Controller is: public JsonResult AjaxTest(string s, int i, bool b) { return Json("S: " + s + "," + "I: " + i + "," + "B: " + b); } My jQuery Code: $(document).ready(function() { $("#btn_test").click(function() { var s = "test"; var i = 8; var b = true; $.ajax({ type: "POST", cache: false, url: "/BizTalk/Services/AjaxTest", data: { i: i, s: s, b: b }, contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { } }); }); });

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9  | Next Page >