Html.Beginform forcing addition of controller name - asp.net

In MVC4, using
Html.BeginForm("/", null, FormMethod.Post, new{something="demo"})
the resulting form has
action="//"
Because it is apparently trying to squeeze the controller and action into the url. However, I'm using the HomeController as the default controller, so I don't want /Home/action in the url. This has been working fine in most places, but this form seems to be tripping me up
Any ideas?

That's not the controller name. You would do something like this:
Html.BeginForm("Index", "Home", FormMethod.Post, new {something="demo"})
If your routes are setup correctly and Home/Index is your default root route, then when rendered, it will render to "/". MVC will automatically optimize the route to show the default minimum (which is the lone "/")
If your not seeing "/" then look at your routes, as it's not able to reverse generate the URL correctly (probably more than one route matches).
If you are using Home/SomethingElse and it's not the default route, then I don't quite get what you're trying to do, since you would be required to specify the Controller/Action to post to it.
While I don't recommend it, you should also be able to do this:
Html.BeginForm(null, null, FormMethod.Post, new {action="/", something="demo"})
I would consider this a hack, however, and I would encourage you to fix the actual route problem.

Related

ASP.Net MVC Controller and View interaction

I created a sample MVC application using following Template.
ASP.NET MVC2 Empty Web Application
Then a added a Controller with the name of First and a right clicked the ActionResult to add a View.
I typed http://localhost:49565/First in my Browser.
Query
How is the controller internally getting to know that a specific page will be displayed when we will type http://localhost:49565/First ?
Moreover, If I add multiple Views for a Controller. How will the system decide which one will be displayed on Priority ?
The controller is invoked by the MVC framework, which uses the routes defined in Global.asax.cs to determine which controller and action to invoke. There is a default route that looks like this:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
When the application receives a request is will try to parse the URL to the format of the routes. If the request is made to http://localhost:49565/, it will use the default values which goes to the Index action in the controller named HomeController. When you have created the new controller, FirstController, and call http://localhost:49565/First, it uses the FirstController instead of the HomeController since it has been provided (but still to the Index action).
Further, when an action is being invoked and there is no view defined explicitly, it will look for a view named the same as the invoked action. In your case it would be ~/Views/First/Index.aspx.
EDIT
If you want to use another view you can specify it in the return statement
return View("OtherView");
and it will use ~/Views/First/OtherView.aspx instead.
Have a look at this blog posts give u the idea of how it is done

asp.net MVC 3 action method

I have created a partial view and I am using it in admin controller's Home action method. Inside partial view, I have an Account Controller with action method named Logon. I am trying to access main view's URL like this
if (Url.ToString().ToLower().Contains("/admin"))
return Redirect("/Admin/Index");
but I cant get the required result. How to get it admin/home ?
From the comments above it looks like you want to just access the current url. If so, then you can simply use the Request object. E.g.
Request.Url.AbsoluteUri
I wonder why you need this though... what is it you are trying to do exactly?

Get the virtual url when using routing with webforms

How do I get the virtual url and not the webforms page name that the url is mapped to when using System.Web.Routing with webforms.
I want the url "/confirm/5" and not "Confirm.aspx".
To get the routed URL for the page you are currently visiting, use Request.Url, as Pavel notes.
If you need to get the routed URL for a different page (such as when creating a hyperlink to another page), use the Page.GetRouteUrl method.
Here's a code snippet showing the use of Page.GetRouteUrl. It's from my article, URL Routing in ASP.NET 4:
lnkCategory.NavigateUrl = Page.GetRouteUrl("View Category", new { CategoryName = "Beverages" });
In the above snippet, "View Category" is the name of the routing rule I want to use. CategoryName is one of the routing parameters and I want to use the value "Beverages". The above call to Page.GetRouteUrl returns the string "/Categories/Beverages". (Of course, the exact string is returns depends on the routing rule "View Category" and the parameter values, but hopefully you get the idea.)
Try the following: System.Web.HttpContext.Current.Request.Url.AbsolutePath

asp.net MVC giving a controller the name 'AdminController' makes it not work

I am working on a ASP.NET application that uses ASP.NET MVC.
I tried naming one of my controllers "AdminController" meaning I typed "Admin" in the new controller text box and it filled out the controller part all by itself of course.
This controller never worked until I changed it's name. If I changed the name to anything else it worked with no problems.
I looked inside my Global.asax.cs file where the routes were configured and I found no routes leading to it.
I tryed adding a route to this new controller like this:
routes.MapRoute("Admin", "calcul/SomeAction",
new { controller = "Admin", action = "SomeAction" });
and it worked but then mysite\admin would only get routed to that specific action.
I renamed the controller to AdminSection and it works but I don't understand why it didn't work before.
Does anyone have any idea
You shouldn't need to create an explicit route for your controller if the default route matches it (controller/action/id).
Also, in the new controller text box you would need to type AdminController rather than just Admin.
The MVC framework will look for classes that end with this when looking for possible controllers.
It was me, there was a area named admin that I didn't see. When I excluded it from the project the "adminController" controller started to work

MVC: capture route url's and pass them to javascript function

Short:Is there a way to have a route-definition that will pass the "CONTROLLER/ACTION" string value to a JavaScript function in stead of actually going straight for the controller action?
More:I have a masterpage which contains the navigation of the site. Now, all the pages need this navigation wrapped around it at all times, but because I didn't want the navigation to constantly load with each pagecall, I changed all my pages to partialviews.
These partial views are loaded via the JQuery.Load() method whenever a menu item is clicked in the navigation.
This all worked very good, up till now because I noticed it's also a requirement of the website to be able to link directly to page X, rather then default.aspx.
So, as an example:The main page is my "default.aspx" page, this utilizes my master page with the navigation around it. And each call to a new page uses a javascript function that loads that particular partial view inside a div that is known in my masterpage. So, the url never changes away from "default.aspx", but my content changes seemlesly.
The problem is, those url's also need to be available when typed directly into the address bar. But, they're partial views, so loading them directly from the address bar makes them display without any masterpages around them. Therefore my question if it might be possible to capture the route typed into the address bar and pass that on to my JavaScript function that will load that route in the content div.
(I hope I explained it ok enough, if not, feel free to ask more information)
You are 100% correct to not want to hard code your URLs in your javascript code as it demolishes one of the primary tenants of MVC to do so. I'm one of those "separation of concerns" guys who will not write a single line of javascript outside of a dedicated .js file so I cannot dynamically specify the URL the way tuanvt has. What I do is use MVCs Url.Action method to emit my service URLs into hidden inputs on the master page (or the specific page if it is not used in multiple places). Then my script file simply pulls the value out of that hidden input and uses it just fine.
ASP.NET MVC View Source
<input id="serviceUrl" type="hidden" value="<%= Url.Action("Action", "Controller") %>" />
JS Source
$.getJSON($("#serviceUrl").val(), function(data) {
//write your JS success code here to parse the data
});
First challenge, as you are using AJAX to load the partial pages you need client accessible URLs for the javascript to call. Second challenge, you need URLs that will load the HomeController and pass the 'page' portion of the URL into the javascript.
For the first aspect I'd create some abstracted routes, i.e. "/ajaxaccess/{controller}/{action}/{id}" for the partial pages. That would be the first registered route. A second route would accept any controller/action reference and always get processed by the HomeController Index action.
In the /Home/Index action you grab the requested URL and slice it up, take the /{controller}/{action}/... section and pass that into your default.aspx using TempData. In your page check for the existence of the TempData and if it exists use the value therein to trigger your AJAX page load for the partial page (don't forget that you'll need to prepend '/ajaxaccess' (or whatever you choose) to the URL before it's passed to your page.
I'm not going to provide code here as I think the information you'll gain from working through this yourself will be invaluable to you moving forward.
You could use hash anchor (#) on your url and read it with javascript.
var url = document.location.toString();
if (url.match('#')) {
anchor = url.split('#');
// do whatever with anchor[1] ..
}
You can do something like this, put this in your javascript code on the view:
var szUrl=<%= ViewContext.RouteData.Route.ToString()%>;
Then the current route will be stored on the variable szUrl.

Resources