Redirecting with slug in Razor Pages - c#

In Razor Pages, how can I redirect to a URL that contains slugs?
For example, the code below takes me to the URL that contains rootValue:
return RedirectToPage("/EmailConfirmation", new {email = command.Email});
The output is like this:
https://localhost:5001/EmailConfirmation/example#gmail.com
But how can I use Razor Pages commands to go to the following URL that contains slugs?
https://localhost:5001/EmailConfirmation?email=example#gmail.com

If you want to go to the following url:
https://localhost:5001/EmailConfirmation?email=example#gmail.com
You can try to use PageModel.Redirect(String) Method:
string queryString = "?email=" + command.Email;
return Redirect("/EmailConfirmation"+queryString);

You could use RedirecToAction,
return RedirectToAction("EmailConfirmation", new { email = command.Email });
Given that you have an action named EmailConfirmation like,
public IActionResult EmailConfirmation([FromQuery] string email)
{
//your code
return View();
}

Related

Razor function to get image path from action

I'm developing a method to display the photo of logged user in a layout page.
It looks like the method is fine, and returns for me the image path, but I don't know to make it works on <img src="">, or I can do it with some razor function?
If I call my method from url like http://localhost:29469/User/LoadPhoto, it returns the correct path.
The layout is not typed, so I can not display it like Model.Attribute
public ActionResult LoadPhoto()
{
if (User.Identity.IsAuthenticated)
{
var userStore = new UserStore<User>(new ERPIdentityDbContext());
var userManager = new UserManager<User>(userStore);
var xUser = userManager.FindById(User.Identity.GetUserId());
string xPhotoPath = HttpContext.Server.MapPath(#"~/Images/Users/") + xUser.FotoPath ;
return Content(xPhotoPath);
}
return View();
}
I want to use return for LoadPhoto method in <img src="">
If your photos are JPGs, return a File ActionResult with the image/jpeg content type:
string xPhotoPath = HttpContext.Server.MapPath(#"~/Images/Users/") + xUser.FotoPath ;
return File(xPhotoPath,"image/jpeg");

Asp.net mvc Url.Action to redirect controller with nullable parameters

I have controller like this:
public ActionResult Load(Guid? id)
{
...
}
When load the view like /Report/Load it load the page.
Then I click on link on page to load one item /Report/Load/7628EDFB-EFD5-E111-810C-00FFB73098ED and it loads the page fine.
Now I want to redirect again to /Report/Load using this url.action
Close Report
But it keeps redirecting me to /Report/Load/7628EDFB-EFD5-E111-810C-00FFB73098ED
What I need to do on URL.Action to redirect me to page with the id?
Tried without success:
Close Report
Thanks
Use:
Close Report
See this answer for more details.
I got it fixed by following answer from johnnyRose and Beyers.
The result is
Close Report
Thanks a lot.
I can't seem to find issue with your code. But Can't you simply set the URL in the model when trying to load the specific item.
In the load function inside the controller do something like this:
var urlBuilder =
new System.UriBuilder(Request.Url.AbsoluteUri)
{
Path = Url.Action("Load", "Report"),
Query = null,
};
Uri uri = urlBuilder.Uri;
string url = urlBuilder.ToString();
YourModel.URL = url;
In your view.cshtml do something like
reports
You should have looked up in your vs's intellisense-
As it accepts arguments- ActionName,ControllerName,RouteValues
Where routeValues is the third argument that is object type and it accepts route values i.e. new{id=9,name="foobar"}
Where method would be like-
[HttpGet]
Public ActionResult Get(int id, string name)
{
}

jQuery to pass to MVC asp.net c# controller

I changed some things around for an item that was requested. This required me to add a parameter to one of the controller ActionResults.
public ActionResult RejectDocument(int id = 0, string rejectReason)
{
IPACS_Version ipacs_version = db.IPACS_Version.Find(id);
ipacs_version.dateDeleted = System.DateTime.Now;
ipacs_version.deletedBy = User.Identity.Name.Split("\\".ToCharArray())[1];
db.SaveChanges();
return RedirectToAction("Approve");
}
Also this link needs to be activated from jQuery after some jQuery items finish. How do I pass this link off now?
should it be href= Document/RejectDocument?id=222&rejectReason=this is my reject reason
could I then do window.location = href; and it would call the controller and pass in the correct information?
You could use the Url helper to create the right url using the table routes rules. For sample:
window.location = '#Url.Action("RejectDocument", "YourController", new { id = 222, rejectReason = "this is my reject reason" })';

A public action method was not found on controller

I am working on a project on asp.net MVC3, I have a controller named UserProfile when i run my project and login, it shows error A public action method images was not found on controller UserProfile
I don't have any action method named images in any of my controllers,below is my UserProfile's index method
[CustomAuthorizeAttribute]
public ActionResult Index()
{
var userName = string.Empty;
if (SessionHelper.GetSession("login") != null)
{ userName = SessionHelper.GetSession("login").ToString(); }
else
{ return View(); }
SessionHelper.SetSess("issetup", null);
UserProfileModel model = GetUserProfileData(userName);
StateandCityDropdown();
return View(model);
}
I have two forms on userprofile index view one with some textboxes and other fields for entering data and second for uploading images
It sounds to me like the routes are picking up on a url you have and mistaking them for an action. It could be that you have a link to an image directory underneath a directory that matches your controller such as /User/Images would thow this error because the routing would then expect you to have an Images action when you dont. Check the page source for anything linking to an images folder but without an image included. The other option is that the routes are picking up the images as well as the actions you want them to. If this is the case in your Global.asax.cs file check the RegisterRoutes method has some ignores in for images.
routes.Ignore("{*allpng}", new { allpng = #".*\.png(/.*)?" });
routes.Ignore("{*allgif}", new { allgif = #".*\.gif(/.*)?" });
routes.Ignore("{*alljpg}", new { alljpg = #".*\.jpg(/.*)?" });
Hope this helps
Andy

ASP MVC Redirect without changing URL(routing)

Goal:
I want to be able to type URL: www.mysite.com/NewYork OR www.mysite.com/name-of-business
Depending on the string I want to route to different actions without changing the URL.
So far I have:
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"UrlRouter", // Route name
"{query}", // URL with parameters
new { controller = "Routing", action = "TestRouting" } // Parameter defaults
);
}
In the controller I have:
public ActionResult TestRouting(string query)
{
if (query == "NewYork")
return RedirectToAction("Index", "Availability"); // <--------- not sure
else if (query == "name-of-business")
return Redirect("nameofbusines.aspx?id=2731"); // <--------- not sure
else
return RedirectToAction("TestTabs", "Test"); // <--------- not sure
}
I have pretty much tried everything to redirect/transfer to the page without
changing the URL, but everything I've tried changes the URL or gives me an error.
Basically I'm looking for the equivalent of server.transfer where I can keep the URL but send info to the action and have it display its result.
I'm with Nick on this one, though I think you could just use regular views instead of having to do partials. You may need to implement them as shared views if they are not in the views corresponding to the controller (since it will only look in the associated and shared views).
public ActionResult TestRouting(string query)
{
if (query == "NewYork")
{
var model = ...somehow get "New York" model
return View("Index", model );
}
else if (query == "name-of-business")
{
var model = ...get "nameofbusiness" model
return View("Details", model );
}
else
{
return View("TestTabs");
}
}
Each view would then take a particular instance of the model and render it's contents using the model. The URL will not change.
Anytime that you use a RedirectResult, you will actually be sending an HTTP redirect to the browser and that will force a URL change.
Im not sure if you tried this way or if this way has any drawbacks..
Add a global.asax file to your project. In that add the following method:
void Application_BeginRequest(object sender, EventArgs e)
{
// Handles all incoming requests
string strURLrequested = Context.Request.Url.ToString();
GetURLToRedirect objUrlToRedirect = new GetURLToRedirect(strURLrequested);
Context.RewritePath(objUrlToRedirect.RedirectURL);
}
GetURLToRedirect can be a class that has the logic to find the actual URL based on the URL typed in. The [RedirectURL] property will be set with the url to redirect to beneath the sheets.
Hope that helps...
You can change your controller like this:
public ActionResult TestRouting(string query)
{
string controller,action;
if (query == "NewYork")
{
controller = "Availability";
action = "Index";
}
else
{
controller = "Test";
action = "TestTabs";
}
ViewBag.controller = controller;
ViewBag.action = action;
return View();
}
Then you can use these ViewBags in your view like this:
#{
Layout = null;
Html.RenderAction(ViewBag.action, ViewBag.controller);
}
That's it. And you can improve this example with use a class and some functions.
Are you saying you want to go to "www.mysite.com/NewYork" and then "really" go "somewhere else" but leave the url alone? Perhaps what you would want to do then is use partial views to implement this? That way, your base page would be what gets routed to, and then inside of that page you do your condition testing to bring up different partial views? I've done that in my application for viewing either a read-only version of a grid or an editable grid. It worked very nicely.
I'm not sure what you can do about the redirect to the .aspx page, but you should be able to replace the RedirectToAction(...)s with something like this:
public ActionResult TestRouting(string query)
{
if (query == "NewYork")
{
var controller = new AvailabilityController();
return controller.Index();
}
else if (query == "name-of-business")
return Redirect("nameofbusines.aspx?id=2731"); <--------- not sure
else
{
var controller = new TestController();
return controller.TestTabs();
}
}

Categories

Resources