How to set urls from controller action in cakephp? - url

I was creating a social networking site, in that each profile page needs to show using a seo friendly url.
Now its like www.siteprof.com/profile/23
i need to add aditioanl string 'jake-web-developer' at the end of this url. result will be like www.siteprof.com/profile/23/jake-web-developer. I know that this can be done when we create profile links. But if someone access this profile using www.siteprof.com/profile/23 this link, can i add that previous text to the url ?
Also is there any method to add these kind of particular string into url from controller actions ?

That doesn't look correct, by CakePHP convention, it should look like:
**www.siteprof.com/profiles/view/23**
After that you set up the profiles_controller to have the action view($id=0,$name="")
I don't know why that is important, but you can generate links with the name parameter and it would still work:
www.siteprof.com/profiles/view/23/jake-web-developer
If it's important to add the last string, then you should do a redirect in the view controller. Check if the $name is specified, and if it isn't, redirect to the URL with the name, although I'd advise against it since it's a performance hit.

My solution would be to put a custom redirect header in the page if the url doesn't contain the SEO friendly title which redirects to the full url
One method would be:
public function view($id = null, $slug = null) {
$data = $this->Profile->findById($id);
if ($slug == null) {
$this->redirect(array('action'=>$view, $id, $data['Profile']['slug']));
}
// .. rest of view logic
}
Hope this helps :-)

Related

MVC Redirect to a different view in another controller

After a user has completed a form in MVC and the post action is underway, I am trying to redirect them back to another view within another model.
Eg. This form is a sub form of a main form and once the user has complete this sub form I want them to go back to the main form.
I thought the following might have done it, but it doesn't recognize the model...
//send back to edit page of the referral
return RedirectToAction("Edit", clientViewRecord.client);
Any suggestions are more that welcome...
You can't do it the way you are doing it. You are trying to pass a complex object in the url, and that just doesn't work. The best way to do this is using route values, but that requires you to build the route values specifically. Because of all this work, and the fact that the route values will be shown on the URL, you probably want this to be as simple a concise as possible. I suggest only passing the ID to the object, which you would then use to look up the object in the target action method.
For instance:
return RedirectToAction("Edit", new {id = clientViewRecord.client.ClientId});
The above assumes you at using standard MVC routing that takes an id parameter. and that client is a complex object and not just the id, in which case you'd just use id = clientViewRecord.client
A redirect is actually just a simple response. It has a status code (302 or 307 typically) and a Location response header that includes the URL you want to redirect to. Once the client receives this response, they will typically, then, request that URL via GET. Importantly, that's a brand new request, and the client will not include any data with it other than things that typically go along for the ride by default, like cookies.
Long and short, you cannot redirect with a "payload". That's just not how HTTP works. If you need the data after the redirect, you must persist it in some way, whether that be in a database or in the user's session.
If your intending to redirect to an action with the model. I could suggest using the tempdata to pass the model to the action method.
TempData["client"] = clientViewRecord.client;
return RedirectToAction("Edit");
public ActionResult Edit ()
{
if (TempData["client"] != null)
{
var client= TempData["client"] as Client ;
//to do...
}
}

Yii url manger with url parameter

What I'm trying to do is when users signup they have a custom url to their own page, like so:
www.mysite.com/username
How do I set the url manager in Yii to achieve this? I know you use this somehow.
<url:[a-zA-Z0-9_-]+>
Also with controller and action with that url:
www.mysite.com/username/controller/action
Put this AFTER ALL the other rules:
// one content type can have special urls
'<username>' => 'user/view',
Assuming your controller's function params are:
public function actionView($username) {
// code to get user by username (instead of by $id)
you can do what ever you want after reading this:
http://www.yiiframework.com/doc/guide/1.1/fr/topics.url#using-custom-url-rule-classes
i advice to read all article! it's helpfull!

Asp mvc redirect without affecting url

I have a rather archaic login system, and this is part of the login action:
// login action
return RedirectToAction("Action", new {
id = aVal,
name = aName,
// other params
});
It redirects the user to the Action action, and i noticed that name and the other params ended up being part of the final url scheme. I need to pass all those values to Action.
[HttpGet]
public ActionResult Action(int id, string name, ...) {
Is it possible to pass them to Action and having the url like this: /Controller/Action/123.
I need to restrict the Action method to only those who pass through the login action, the long url + query string make it almost impossible to make it through, but is there another more profesional way to do it.
Thanks and greetings to the SO and SE community.
In order to get Restful styled url's you need to setup an appropriate route.
So in your case something like
routes.MapRoute("MyRoute", "MyController/MyAction/{id}/{name}", new { controller = "MyController", action = "MyAction" });
you can see some other examples here
The second part of your question is more vague - you may want to tag your class with an [Authorize] attribute and then override OnAuthorization where you can do any checks. Not sure if this is what you are looking for.
There is an example of this here

Pass relative URL ASP.NET MVC3

I'm trying to pass a list of URL's with Id attributes from a controller to a view.
I can pass a <a href=...> link back but I don't think writing a 'localhost' absolute path is a clean way of approaching this. I cant pass an ActionLink back as it returns the full string. Is ther a simple solution to this problem? Thanks in advance.
Using this overload of the UrlHelper.Action() method and Request object you can get a complete URL including the route parameters such as IDs and the actual hostname of the application.
string url = Url.Action("action", "controller",
new System.Web.Routing.RouteValueDictionary(new { id = id }),
"http", Request.Url.Host);
UrlHelper is available in the controller via its Url property.
You can then pass such URL into your view.
It is also possible to use UrlHelper directly inside your view to create URLs for controller actions. Depends if you really need to create them inside the controller.
Edit in response to comments:
Wherever you need to place the URLs, this "URL builder" you are looking for is still the UrlHelper. You just need to pass it (or the generated URLs) where you need it, being it inside the controller, view or custom helper.
To get the links inside the unsorted list HTML structure you mention, you need to put anchors inside the list items like this:
<ul>
<li>Link</li>
...
</ul>
Then again you just need to get the URLs from somewhere and that would be from UrlHelper.
Simple and easy.
text
the route id = the parameter that is going to be inserted into your method.
eg.
function Details(int id) {
//id has the value of my_var_id
}

How do I specify a return url for a link to the login form?

Simple enough, it would seem, but it turns out not to be - mainly due to the fact that the View can't possibly know which way through Model and Controller you got there. Regardless, it is a problem that needs a solution:
I have a login link, that takes the user to a form to enter username and password. When the user clicks "submit", I want to redirect to the page he was viewing. The easiest way to do so seems to be specifying the url to the current page as a querystring (...?returnUrl=...) and everything else is already built.
But where do I find this url from my view, when rendering the link? I naturally can't use a RedirectToActionResult as I don't want to actually transfer the user - only render the url in a link. How to?
EDIT:
I have now started a bounty on this question, and therefore I see fit to clarify my needs as well.
I have a UserControl named Login.ascx in my Shared folder. In it, I render an ActionLink to the login form, and it is included in the footer on my Masterpage. What I want to accomplish is the following:
When the ActionLink is rendered, the querystring returnUrl is appended with the a route to the view that is currently being rendered. If this is accomplished, the user will be taken back to the page he/she was viewing after successful login with functionality that is already build into the ASP.NET MVC Framework.
The reason the previous answers have not been sufficient is mainly that they have not provided a way to build the route url to the current view. I do know how to append a querystring, but I do not know how to find out what to put in that string.
In order to mark an answer as the answer, I want a method to re-construct the route to the currently shown view, from a usercontrol in the masterpage.
The solution is to use HttpContext.Current.Request.RawUrl like this:
<%= Html.ActionLink("log on", "LogIn", new { controller = "User", returnUrl = HttpContext.Current.Request.RawUrl }) %>
Or with an extension method from MVC futures (Microsoft.Web.Mvc.dll):
<%= Html.ActionLink<AccountController>(c => c.LogOn("name", "password", false, HttpContext.Current.Request.RawUrl), "login here")%>
ActionController is the default one in mvc but just add returnUrl to your own.
One way would be to build the links that send the user to the login form, with returnUrl=/PageToReturnTo (Login for example). You'd want to write it so the return url was constructed from your routes though, manually writing those links on every page could be cumbersome.
The default login action in MVC has the returnUrl functionality already built. Just need to pass it a value and it will do the rest. Here's a copy'n paste of the method signature from a fresh project.
public ActionResult Login(string username, string password, bool rememberMe, string returnUrl)
Hope that helps ya!
You can use Page.Request.Url to get the route that resulted in the currently rendered view.
Though that's more of a cosmetic detail, you might want to unify the requests that came through the '/' and '/default.aspx' routes and always return to the '/' route. I have a helper property in my master page that does exactly that.
protected Uri RouteUrl
{
get
{
if (Page.Request.Url.AbsolutePath.StartsWith("/default.aspx", StringComparison.OrdinalIgnoreCase))
{
return new Uri(Request.Url, new Uri(Response.ApplyAppPathModifier("~/")));
}
return Page.Request.Url;
}
}
I don't know about ASPX, but there are a couple of problems we encountered building this:
When the user gets their password wrong, and loops-round the Login page to have another go, the Target must still be preserved.
We also decided to preserve POST variables to a page that then required the just-in-time login

Resources