mvc routing - Passing data to a display controller from the Route - asp.net-mvc-3

I have a route like the following:
/Company/1234/Contact/3456
The general pattern for my routes is that strings are actions/areas and numerics are the records ids.
In the Contact controller (action{edit}) I want to pass in the id from the company and the contact.
Is there a way in the framework to get that information? Or do I need to parse all numeric values in the route in order to know which is what?
Any help would be great.

Based on an other question I asked MVC3 Routing - Routes that builds on each other
The solution would be to name my routes correctly, with each id having a unique name.
Company would be CompanyId, contact would be ContactId.
/Company/{CompnayId}/Contact/{ContactId}
Then in the controller method the signature could look like:
ActionView Edit(int CompanyId, int ContactId))
{
...
}

Related

Laravel 5.8 - one route two different controller action

In laravel 5.8, I have have 2 type of url.
/news/{category} - > send to news controller index action, if have category bind
/news/{news} - > send to news controller details action, if have news bind
Another case abort with 404.
How can i solve this problem?
In Laravel and almost all frameworks and routing systems I'm aware of, the Route and Controller/Action relationship is 1:1. Each route can only have one controller or action to handle it.
If I understand your question correctly, you have a single route pattern of /news/{parameter}, and you want one of three things to happen:
{parameter} contains a valid Category slug. Retrieve the category and display the appropriate view.
{parameter} contains a valid Article (details) slug. Retrieve the article and display the appropriate view.
{parameter} does not contain a valid category or article slug, and thus is not found. Return a 404 error.
You'll still need only a single controller action, but you can separate the logic to make it easy to understand:
routes/web.php:
Route::get('/news/{param}', 'NewsController#index');
app/Http/Controllers/NewsController (with pseudo code):
class NewsController extends Controller
{
public function index(string $param)
{
if ($category = Category::whereSlug($param)->first()) {
// Return your category view.
}
if ($article = Article::whereSlug($param)->first()) {
// Return your article view.
}
\abort(404);
}
}
I would personally recommend against sharing a common URL structure for two different entity types like this. It opens the possibility for name conflicts (a Category and Article have the same slug) and can make the user experience confusing. (It might hurt search engine optimizations or results, also, but that's just speculation - I don't have anything to confirm or deny that.)

change laravel resource url

is there a way to customize Laravel 5 resource URLs ?
For example, change user/1/edit to user/edit.
That's because I don't want anybody to see the id in the URL. I think it is database information and shouldn't be revealed.
The point is that I want to do this without changing my routes. On the other hands I want to do this by using resource routes I have and not by adding some new routes to them , as you know when you define a resource route in your project it automatically adds some predefined routes to the route table and you are forced to use them in the way they are. For example you have to send a GET request to user/{user} for showing the user. Now I want to have a URL like user/{username} for doing this without adding a new route, IS THAT EVEN POSSIBLE?
if there is a way for achieving this I appreciate it if you share it here.
Thanks a lot
Since in most cases id is an auto incremented value and guessable, better you can use any other unique column of users table here, e.g username and then using that column instead of id in resource controller. Suppose you've an unique username column in your table So, if you use that instead of id your call to user edit will be like:
{!! route('user.edit', $user->username) !!} // let's say username is shahrokhi
which is equivalent to
user/shahrokhi/edit
Now for example, in your resource controller to edit a user details code may be like:
public function edit($username)
{
$user = User::where('username', '=', $username)->firstOrFail();
// rest of your code goes here
}
And so on for other methods.

Dynamic URL structure with Spring 4

We have a Spring MVC webapp and our product URL structure needs to be SEO friendly. Such as www.mydomain.com/{productname}. Every time we add a product to inventory, we want to have URL to display those product details.
We could not figure our how to generate dynamic URLs with Spring Controller Resource path.
Can someone please help us.
Would appreciate your help.
Thanks
Raj
A Spring URL structure like www.mydomain.com/{productname} would seem to imply that 'productname' is always unique. If so, each product could have a property called 'name' or 'productname'; this property could be used to retrieve the relevant product in your controller method. This will only work if every 'productname' is unique.
What you are looking for is URI Template Patterns. In Spring MVC, #PathVariable annotation is used to bind an argument to the value of URI template variable.
#RequestMapping(path="/{productname}", method=RequestMethod.GET)
public String findProduct(#PathVariable String productname, Model model) {
List<Product> product = productService.findProductsByName(productname);
model.addAttribute("product", product);
return "displayProduct";
}
Note that the service call returns List<Product> instead of one Product, since ideally, product name is not unique to one item. If you want the URI to identify exactly one product, make sure that product name is unique to one product only.

URL rewriting in MVC3

I am working on a project for a local college using MVC3. I have came across a requirement at which I am stuck and can't find any wayout.
Let suppose my URL is www.abc.com
The requirement is that if we type teacher name after the URL we get the detailed view of the teacher, like:
www.abc.com/john
www.abc.com/smith
I asked for option like www.abc.com/teacher=john but it has been rejected.
Is this something relevant to URL rewriting or some other wayout, as there can be many teachers in database so I can't make methods in controllers for every teacher.
Can anyone please guide me for this scenario?
Kind Regards
MVC does this natively.
Just create a route for it:
routes.MapRoute(
"Teacher route",
"/{teacher}",
new { controller = "SomeController", action = "SomeAction" }
)
Note that this will conflict with any other /Whatever URLs (eg, /About); to avoid that, you can use my MapDefaultController() extension to map a route for a specific controller before this one.

MVC3 Routing - Routes that builds on each other

I have an AREA setup in my project. I need to make the routes for the area progressive, meaning that the route will build on each other.
I'm looking at this as something like a link list. Each node in the list will have a reference to a parent. As move from left to right in the list it builds, and from right to left it removes.
In the area, I have companies and that have contacts, and child companies.
For example, I have companies that would have the following:
/Companies/list
/Company/{Id}
/Company/{id}/add
/Company/{id}/edit
/Company/{id}/delete
For the contact section I need to create the following routes:
/Company/{id}/contacts/list
/Company/{id}/contact/{id}/add
/Company/{id}/contact/{id}/edit
/Company/{id}/contact/{id}/delete
How do I make sure that /Company/{id} is always in the Contact and Child Company sections of the route?
I hope that I have made my question clear.
Subjective Generalities (take with a pinch of salt):
First off, you are using Company (singular) for companies, but then you are using contacts (plural) for the contacts. There is nothing wrong with this, from a structural point of view, but your users will thank you if you are consistent with your pluralizations. I would use the plural in both cases, but that is just my preference... it looks more like English.
You also use lower case for contacts, but upper case for Company. Doesn't look professional.
The next thing that is confusing is that you are using two {id} parameters, one for companies, one for contacts. I presume these are the ids for Company and Contacts respectively. But I am confused, but being human, I am able to deduce context unlike a computer. So you would be better of specifying the parameters in your routes. Ie:
/Companies/{CompanyId}/Contacts/{ContactId}/[action]
Answering your Question with an Example:
I get the feel you don't understand routes properly. If you did, your question would be more specific.
Your route parameters can come from a number of sources, depending on how the route is requested.
You could hard code it into a link. Or, more usefully, your route registration would be designed to catch requests that map to your Action signatures.
For example, I have an eLearning app with tutors, pupils, courses and steps (ie, the steps are like sections of a course, the pupil advances through the course step by step)
The route registration looks something like:
Route or Area Registration:
context.MapRoute(
"StepDisplay",
"Course/{CourseId}/Step/{StepOrder}/Pupil/{PupilName}/{TutorName}",
new { controller = "Course", action = "Display", TutorName = UrlParameter.Optional },
new[] { "ES.eLearningFE.Areas.Courses.Controllers" }
);
This route will catch a request from the following ActionLink:
ActionLink in View:
#Html.ActionLink(#StepTitle, MVC.Courses.Course.Actions.Display(Model.CourseId, step.StepOrder, Model.Pupil.UserName, tutorName))
Now, I just need to show you the Display action's signature:
CoursesController:
public virtual ActionResult Display(int CourseId, int StepOrder, string PupilName, string TutorName)
There are a few things to note here:
That I am able to call this specific route by giving the user a link to click on.
I construct this link using the Html.ActionLink helper
I have used David Ebbo's t4mvc nuget package so that I can specify the action I am calling and its parameters. By which I mean specifying the ActionResult parameter of the Html.ActionLink helper using:
MVC.Courses.Course.Actions.Display(Model.CourseId, step.StepOrder, Model.Pupil.UserName, tutorName)
If you think about it, what routes do is translate the url of a request into an action, so the parameters of my route are either the controller name, the action name or else they are the names of parameters in the action signature.
You can see now why naming two distinct route parameters with the same
name is such a bad idea (largely because it won't work).
So, look at your action signatures, and design your routes and your action links so that the everything marries up together.
MVC doesn't work by magic!! (Although the way it uses name conventions might lead you to believe it)

Resources