How to pass parameters in ASP.NET MVC for attributed routes - asp.net-mvc

Here is my model:
Company-->Projects
I created my company which has id = 1. Now, I want to add a project to it. Using MVC attribute routing I am able to go this URL fine: http://example.com/companies/1/projects/create
When I fill in the fields for the project and submit it using HTTPPOST I want to send the user to http://example.com/companies/1/projects/edit/9 <-- 9 being the project which just got created from the create method.
If I do this:
return RedirectToAction("{companyid}/projects/edit", "companies", new {companyid = id, id= project.ID });
it goes to here and blows up: http://example.com/companies/%7Bcompanyid%7D/projects/edit/9?companyid=1
I want it to go to http://example.com/companies/1/projects/edit/9
Can anyone help me figure out the RedirectToAction() for this please?

The first argument to RedirectToAction is an action name (so the name of the method that will get called on your CompaniesController), not the route.
You can either substitute your string "{companyid}/projects/edit" for the action name or use the RedirectToRoute method and pass in the name of the route as set up in your routing tables.

Related

Html.BeginForm does not redirect to action Method

I try using Html.BeginForm to submit my data but it does not help me with it. I followed this link to make my mvc program: https://www.c-sharpcorner.com/UploadFile/f82e9a/form-data-submiting-and-displaying-data-another-view-using-m/
#using (Html.BeginForm("SubmitEmp","ClientController",FormMethod.Post))
using this I get the following error:
My view has a folder named Client, in which there are two files:
Index: this contains the form.
this the view to get the details entered in the previous form.
My controller (ClientController) has the code mentioned in the link
and my Model is Cmodel with the same code.
Your Code should be like this then it will work
#using (Html.BeginForm("SubmitEmp","Client",FormMethod.Post))
We cannot and use full controller name like ClientController for specifying controller name we need to specify only the name of Client
In your URL localhost:5000/ClientController/Submitemp showing controller name ClientController it should be Client only change your URL like localhost:5000/Client/Submitemp then it will work.
Cheers!!
No need to pass "Controller" in controller name, simply pass "Client". Make sure you have "SubmitEmp" HttpPost action in Client Controller
I can see that you have passed controller name as 'ClientController' which appears to be incorrect. The Controller in 'ClientController' represents that this is a Controller named Client. You can pass 'Client' instead of 'ClientController' in the place for controller.

Html.RenderAction with Route Name

I am trying to utilize the Route attribute naming (ex: [Route(Name = "Abc123")]) in a controller action, and likewise be able to call that via Html.RenderAction, but it appears that this does not support route names. I assume this is because route names are reserved only for ones requested via HTTP and not called directly, but somewhat new to MVC so I'm at a loss.
I'm using MVC Attribute Routing entirely, and I do not have routes configured otherwise. It seems that I must define the route name, and the route name has to match the action method name. In doing so, however, I am getting naming conflicts when I try to name more than one Index.
I'm basically trying to support multiple partial views, each having their own controller, which serve as plugins/widgets on my site. So ideally each would have an action called Index.
Do you have a recommendation on how I can maintain the same naming? This allows me to call Html.RenderAction("Index", [ControllerName], [Model]) without the render name changing.
You can use attribute routing with Html.RenderAction just you have to make sure that the action name in attribute is actual Name :
[Route("Home/About")]
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
and in HTML you can have
#{Html.RenderAction("About", "home");}
It will work fine.
You should be able to do what you are trying to do with attribute routing. If you are trying to render a partial view you should be using RenderPartial instead of RenderAction.
Are you doing this between areas? I believe there are some gotcha's with making that work correctly.
Can you please post example Controller code and RouteConfig?

ASP.NET MVC Dynamic Action with Hyphens

I am working on an ASP.NET MVC project. I need to be able to map a route such as this:
http://www.mysite.com/Products/Tennis-Shoes
Where the "Action" part of the URL (Tennis-Shoes") could be one of a list of possibilities. I do not want to have to create a separate Action method in my controller for each. I want to map them all to one Action method and I will handle the View that is displayed from there.
I have this working fine by adding a route mapping. However, there are some "Actions" that will need to have a hyphen in them. ASP.NET MVC routing is trying to parse that hyphen before I can send it to my action. I have tried to create my own custom Route Handler, but it's never even called. Once I had a hyphen, all routes are ignored, even my custom one.
Any suggestions? Details about the hyphen situation? Thanks you.
Looking at the URL and reading your description, Tennis-Shoes in your example doesn't sound like it should be an action, but a Route parameter. Let's say we have the following controller
public class ProductsController : Controller
{
public ActionResult Details(string product)
{
// do something interesting based on product...
return View(product);
}
}
The Details action is going to handle any URLs along the lines of
http://www.mysite.com/Products/{product}
using the following route
routes.MapRoute(
null,
"Products/{product}",
new
{
controller = "Products",
action = "Details"
});
You might decide to use a different View based on the product string, but this is just a basic example.

ASP.NET MVC Action Parameters with Binded prefix not compatible with Url.Route in Global.asax

I have a details page containing a form field named UserId. On the same page i have another search form with a field also named UserId.
I am using Html.LabelFor(vm > vm.UserId) and Html.TextBoxFor(sm > sm.UserId) on the two different view models, vm being the view model and sm being the search model. (Yes, the UserId property on the two models has identical names - because they are the same domain property.
When i navigate to the page, the populated UserId on the vm is inserted into BOTH form fields named UserId by MVC. Even the sm.UserId are empty.
That is my initial problem. There are a few ways ti avoid that. My solution was to use the Prefix flag for the sm.
[HttpGet]
public ActionResult Search([Bind(Prefix = "Search")] SearchFormViewModel searchFormViewModel, PagingViewModel pagingViewModel)
{
This will provoke MVC to render a Search.UserId on the fieldname in the search form, but the property in code will still be named UserId.
This solution seems to work great!
BUT:
Now i have to address the search.UserId on a route from Global.asax.
I map the route like this:
routes.MapRoute(
"MyRouteName",
"ControllerName/User/{Search.UserId}",
new { controller = "ControllerName", action = "Search" }
);
My problem is that MVC can't map the Search.UserId (because of the .) to fit the UserId (prefixed with Search) in the action shown above.
So it seems like MVC has a prefix-feature, that are actually nok fully supported through the Route-handler.
Ofcourse i could rename the Search.UserId to Search_UserId, but then the name dosent match the name MVC expects in the recieving action above. (expects Search.UserId) Renaming The UserId property of the search model would fix the issue, but since it is the same value in the domain, this seems like a workaround.
Am I missing something here about the usage of the Prefix feature or is this just not possible?
So... I've been thinking about this for a while now. - And a colleague of mine suddently showed me the light.
The problem lies where MVC maps the object to a route dictionary.
See the user
wount work. Because MVC can not handle the .(dot) in the object name.
but since the object name is just a string key in the routevaluedictionary, mapping it my self did the trick:
See the user

ASP.NET MVC Routes: Conflicting action names with custom route

i all,
In a previous question, I asked how to define a custom route to handle the following URL:
http://www.example.com/User/Profile/Edit/{userProfileID}
I have a User object and a UserProfile object, but only a UserController that I want to be able to use for actions on both objects. I already have a method in UserController called Edit that handles edits on a User. But I also need a method for edits on a UserProfile. The answer to my routing question was the following route:
routes.MapRoute(
"ProfileleRoute", // Route name
"User/Profile/{action}/{userProfileID}", // URL with parameters
new { controller = "User", action = "Index" } // Parameter defaults
);
But given that custom route, where should I be declaring the edit action for a UserProfile, and what should it be called? It seems like I couldn't write another method in UserController called Edit because I already have one that handles User edits.
So I feel like I would end up with a need for two Edit actions to handle the following routes: "User/Edit" and "User/Profile/Edit". How do I get around this?
Thanks very much.
When the framework it's going to select what action to execute it first check the actions with the name required with a HttpPost ot HttpGet attribute that match the request, if not action is selected this way, then it select any action that match the name.
So, if you have two actions with the same name with no HttpPost or HttpGet attributes, you can't control with action is going to get executed.

Resources