I have a route config file that I'm trying to route all URLs that follow the formula .com/{a page}/{a subpage}, to route to a specific page .com/Default/Page.aspx. My problem is that it does this for all the pages (i.e., .com/Account/Login.aspx. Is there a way to specify that I want it to route to that page only when a user types it into the address bar, possible only when they leave out the .aspx extension? This is what I have so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.Membership.OpenAuth;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;
namespace CouponsForGiving
{
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.Ignore("{resource}.axd/{*pathInfo}");
routes.MapPageRoute("LearnMore", "LearnMore", "~/LearnMore.aspx");
routes.MapPageRoute("DefaultPage", "{nponame}", "~/Default/NPOPage.aspx");
routes.MapPageRoute("CampaignPage", "{nponame}/{campaignname}", "~/Default/CampaignPage.aspx"); //This one routes a lot of other pages
routes.EnableFriendlyUrls();
}
}
}
Thanks!
Issue here is with the overriding of a route. If there are 2 routes with same number of parameters and if there is no hard-coded value, it will always consider the first route, which is declared. For Example, if following 2 routes are registered,
routeCollection.MapPageRoute("LearnMore", "{param1}/{param2}", "~/About.aspx");
routeCollection.MapPageRoute("DefaultPage", "{param3}/{param4}", "~/Account/Login.aspx");
In the above case, the route LearnMore will only be consider as valid which will be requesting About.aspx page.
You can do something like below:
routeCollection.MapPageRoute("LearnMore", "learnmore/{param1}/{param2}", "~/About.aspx");
routeCollection.MapPageRoute("DefaultPage", "default/{param3}/{param4}", "~/Account/Login.aspx");
This will redirect to the respective pages. You can go through below URL for more details on URL Routing.
http://karmic-development.blogspot.in/2013/10/url-routing-in-aspnet-web-forms-part-2.html
Thanks & Regards,
Munjal
Related
When I create a new Razor page in Visual Studio 2017, the separated code behind file did not get created.
This is the screenshot of the problem highlighted.
We can see the Razor page called List.cshtml does not contain the code behind file. Contrast that with the default page about.cshtml, for example.
1 - Right click on "resturants", add class:
2 - in your case, call it List.cshtml.cs. This will create the code behind. It nows needs wiring up. Open the class that has been created.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
//Add the MVC usings
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
//TODO The namespace will be correct in your code
namespace app_name.Pages.resturants
{
//public class List
//TODO correct the model name and inherit PageModel
public List1Model : PageModel
{
public void OnGet()
{
}
}
}
3 - In List.cshtml:
#page
#model app_name.Pages.resturants.List1Model
#{
}
More information can be found here on modifying the code behind https://learn.microsoft.com/en-gb/aspnet/core/data/ef-rp/sort-filter-page?view=aspnetcore-5.0
I'm having trouble setting up a routing convention for Razor Pages in an ASP.NET Core 2.2 application (I'm migrating from traditional MVC to Razor Pages).
I am using the standard Pages folder structure as recommended in the documentation, but I want to customise the generated routes slightly.
For example, on a Details.cshtml page in the Products folder I have the following directive:
#page "{id:int}
The URL for this page is:
/Products/Details/42
however I want the URL to be:
/Products/42
I want this to be globally applicable, not just on the Product Details page. The documentation is not particularly clear on this.
So this seems to be the way to do it:
https://www.mikesdotnetting.com/article/327/customising-routing-conventions-in-razor-pages
Create a class that implements IPageRouteModelConvention:
public class CustomPageRouteModelConvention : IPageRouteModelConvention
{
public void Apply(PageRouteModel model)
{
foreach (var selector in model.Selectors.ToList())
{
var template = selector.AttributeRouteModel.Template;
if (template.EndsWith("Details/{id:int}", StringComparison.OrdinalIgnoreCase))
selector.AttributeRouteModel.Template = template.Replace("Details/{id:int}", "{id:int}", StringComparison.OrdinalIgnoreCase);
}
}
}
Register the class in Startup.cs:
services
.AddMvc()
.AddRazorPagesOptions(o =>
{
o.Conventions.Add(new CustomPageRouteModelConvention());
});
Compared to the old MVC way of doing it this seems like a massive effort, but I can see that it allows for a finer level of control.
You need to override the entire route, so this is what you needed -
#page "/Products/{id:int}"
I am new to Sitecore and .NET. I got an old existing project which is based on Sitecore 6.5 and rendered content by XSLT with .NET Framework 3.5.
Now what I need to create a page that can make an AJAX call so that the page need not to be refreshed and new content can be generated. I am quite familiar with AJAX call with PHP, yet I am quite confused on those in .NET.
I googled and found most of the tutorial are based on Razor view rendering.
Can anyone provide me a full picture that how can I do to meet my objective?
I wonder if the following steps are correct:
Create a .xslt for rendering different content based on matching the URL parameter that passed into
Create a .ashx to get the .xslt content
JavaScript AJAX call to the .ashx and convert the xml content to HTML
Any examples that I can follow?
Thanks!
============================================
Update:
I tried the above flow and can print Hello World by AJAX successfully.
However, I am not sure how to get the content from XSLT in the following .ashx file with different parameter?
And are there any HttpPost/IsPostBack that can help to check if the .ashx is visited by a POST method?
I finally solved the question with the following steps.
Create a .ashx to render the sitecore content.
I have compared with .ashx, .aspx and .asmx. Seems .ashx is the best choice.
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MYPROJECT.Web
{
/// <summary>
/// Summary description for AjaxTest
/// </summary>
public class AjaxTest : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
string ID = context.Request.QueryString["ID"];
Database master = Factory.GetDatabase("master");
Item source = master.GetItem("/sitecore/content/Home/MYPROJECT/gallery");
Item[] items = source.GetChildren().ToArray();
context.Response.Write(items[ID].Fields["image"].Value);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
p.s I removed some validation codes from above.
JavaScript AJAX call to the .ashx.
$j('#ajax_test').click(function(){
$j.ajax({
//type: 'POST',
url: '/AjaxTest.ashx?ID='+$j('#inputunmber').val(),
//dataType: 'html',
//data: form.find(':input').serialize(),
success: function( response ) {
$j('.test_result').append(response);
},
error: function (xhr) {
alert("Error:" + xhr.responseText);
}
});
});
I've been assigned to rewrite some existing ASP.NET pages using MVC. Prior to working on this assignment I was completely uneducated on MVC.
The pages I'm working on are simple reports that accept parameters from the user, pass the parameters to a stored procedure (SQL Server) and return a set of data which is displayed on a web page.
Prior to my arrival on this project a previous team member had been in the process of converting these pages to MVC. He left before I arrived. Now I have been assigned to continue the task of converting these pages to MVC.
I've worked through some MVC tutorials on W3schools and Channel 9, and those made sense to me. I was able to get those simple tutorial apps up and running without any trouble. But I'm having a whole lot of trouble converting these 'real' pages to MVC.
I say "converting", but what I mean by that is that I'm leaving the existing pages alone and building a new MVC "page" that mimics the behavior of the existing page.
I've been working under the assumption that I could create a new controller, then build a new view off of the new controller, then run my application and navigate to the new view by typing it's associated URL into the browser's address bar. But when I try this I get a 404 error.
No one else on my team is familiar enough with MVC to give me any kind of advice. I have no idea how to troubleshoot this situation. I'll provide as much specific information as I can about the project I'm working on, I'm just not sure what details to provide at the moment.
So in summary, what I'm asking for right now is some help on how to create a new view in this existing application and how to get the application to successfully display the view when I attempt to navigate to it's URL.
Thanks.
Edit:
I've started out with a very simple controller, just to see if I could get the application to display its associated view. The controller isn't meant to do anything other than display its associated view. Here's the code for it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace TSS.Controllers
{
public class Tim_Dev_Controller : Controller.
{
//
// GET: /Tim_Dev_/
public ActionResult Index()
{
return View();
}
public ActionResult Test()
{
return View();
}
}
}
Edit 1.1:
Here's code for the corresponding view:
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>
Edit 2:
Here's the contents of the routeconfig.cs file:
using System.Web.Mvc;
using System.Web.Routing;
using TSS.Utilities;
namespace TSS
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{instance}/{controller}.aspx/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "CTPCatalogImportEmployee",
url: "{instance}/{controller}.aspx/{action}/{empId}/{series}"
);
}
}
}
Edit 3:
Here's a little more information. I can place a break point in the existing controllers where they call
return View()
and hit those break points when I open those pages. But when I place a breakpoint at the same
return View()
call in my new controller it never gets hit. (This is when I try to navigate to my new view by entering the associated URL into the address bar of the browser. )
You should ignore the old aspx files, and keep the routes without .aspx
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{instance}/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "CTPCatalogImportEmployee",
url: "{instance}/{controller}/{action}/{empId}/{series}"
);
}
Occasionally I have a tendency to overlook the obvious. I never bothered to rebuild my solution after adding the new controller and view. Once I did that the controller fired and pulled up the view without any trouble.
[sigh]
Thanks everyone, for your help.
UPDATE1
I've added RazorGenerator and etc...
After set custom tools, I've seen generated code for my razor pages.
Added this code in assembly
public class MyAreaRegistration : AreaRegistration
{
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute("Dictionary_default", "MyDictionary/{Action}/", new { controller = "DictionaryControllerBase", action = "Index" });
}
public override string AreaName
{
get { return "MyDictionary"; }
}
#endregion
}
But when I open page by url /MyDictionary, i see "Unable to find the resource."
NOTE I use in my project MVC3 and Spring.Net
I use one controller (base controller) in another Assembly with razor pages.
In my project I make controller inherited from base controller, just it make some settings. But razor pages I wish to use from assembly.
How can I do it?
You could the RazorGenerator extension. I have detailed how this can be achieved in the following post. The idea is that the RazorGenerator extension would create a corresponding .cs file for each Razor view and it will update it every-time you make a change to the corresponding view. This way the Razor views will be precompiled in the class library along with their respective controllers and view models. The RazorGenerator.Mvc NuGet will then register a custom virtual path provider which will take care of resolving those views.