Given htmlHelper + action name, how to figure out controller name? - asp.net-mvc

How does HtmlHelper.ActionLink(htmlhelper,string linktext,string action) figures out correct route?
If i have this=>
HtmlHelper.ActionLink("Edit","Edit")
Mvc automatically finds out correct route.
i.e. - if controller was Product, it will render anchor with href product/edit.
So - how to figure out controller name when i got htmlHelper + action name combo?

If your HtmlHelper looks something like:
public static string MyHelper(this HtmlHelper htmlHelper,
... some more parameters ...) {
return ... some stuff ...
}
Then from your helper, access:
RouteData routeData = htmlHelper.ViewContext.RouteData;
string controller = routeData.GetRequiredString("controller");
The RouteData object contains all the values that were processed by ASP.NET Routing for the current request. This will include the parameter names and values from the route, such as "{controller}/{action}/{id}". Many of the built-in ASP.NET MVC helpers grab "ambient" data from there so that the developer doesn't have to type them in for every helper they use.
You can also download the full source code to ASP.NET MVC from here:
ASP.NET MVC 1.0 RTM source code
ASP.NET MVC 2 Release Candidate source code

Related

ASP.Net Core 2 - Using Url.Action to generate url to web api behaves differently?

I've used the helper Url.Action to pass relative URLs from MVC views to Typescript/Javascript classes before in full ASP.Net MVC with success. Here is an example, in a cshtml file:
<script>
let vm = new VM('#Url.Action("Names", "api/Data")');
</script>
The Typescript class constructor is passed the following string in full ASP.Net: "/api/Data/Names", but in ASP.Net Core 2, the passed URL is "/api%2FData/Names", which is an invalid URL. I can't figure out if this is intended or a bug.
Url.Action(action, controller)
Specify the controller name, not the route, e.g...
Url.Action("names", "data")
And then on the controller itself you can do something like...
[Route("api/data")]

how to create hierarchy of pages in asp.net MVC

I am working on a classified website that will have links like "electronics/mobiles/samsung/samsungS3/adTitle". How to create hierarchy of views like that in asp.net. If the answer is HMVC then please refer some link that contains complete guide how to implement HMVC.
You don't need hierarchy of Views, you should use Route Config that will allow you to get View that you need base on URL.
From 4 Version of MVC also have areas not only controlles and View by default. So check this tutorial to know how to customise your Routing.
You don't need to create views in this hierarchy but you need to create URLs in this fashion and that is called friendly URLs.
Look at following stack overflow question
How can I create a friendly URL in ASP.NET MVC? and Friendly URL
You will be defining another route which will end up on your single action method. So You will add a route in routeConfig.cs as follows
routes.MapRoute(
name: "custom",
url: "{category}/{type}/{manufacturer}/{version}/{Title}",
defaults: new { controller = "Home", action = "customRoute"}
);
and your custom action will have all values passed in as param be as follows
public string customRoute(string category, string type, string manufacturer, string version, string Title)
{
return category + type + manufacturer + version + Title;
}
You can achieve the same using action based routing as well
// eg: electronics/mobiles/samsung/samsungS3/adTitle
[Route("{category}/{type}/{manufacturer}/{Title}")]
public ActionResult Index(string cateogry, string type,string manfacture, string Title) { ... }

Access to current AntiForgeryToken to HtmlHelper

Can I access to current AntiForgeryToken that generated in view to HtmlHelper extention method?
Something like this:
public static string AntiForgeryTokenValue(this HtmlHelper helper)
{
}
You can get current anti forgery token value from incoming request... like below
MVC keeps this value in hidden form field with name __RequestVerificationToken...
HttpContext.Current.Request.Headers["__RequestVerificationToken"]
You can also get in client side like below :-
$('input[name="__RequestVerificationToken"]').val()
(But why do you need its value in HtmlHelper while rendering view)

ASP.NET MVC catch URL parameter in Controller

I've defined such a controller ViewProfile.
I want to use it for the next syntax to access public user info in my project.
/ViewProfile/Sammy
/ViewProfile/Billy
etc...
But I don't know how to handle the 2-nd parameter in URL.
I've tried to use:
[HttpGet]
public ActionResult Index(string query)
{
...
return View();
}
But in the debugger, string query is always empty.
I have read about routines mapping, but really don't understand how would it help me with the determination of id or other parameters.
I read in ASP.NET MVC Book that to get the parameter directly in the controller action just name it as ID.
ASP.NET MVC lets you easily do this without having to confi gure
anything extra. ASP .NET MVC’s default routing convention is to treat
the segment of a URL after the action method name as a parameter named
ID. If your action method has a parameter named ID, then ASP.NET MVC
will automatically pass the URL segment to you as a parameter.
I just tried a sample app and it worked fine for me. The string i entered in the URL did get passed on to the ID parameter in the action.
Also what i noticed is that you should provide your URL as viewprofile/index/1 or
viewprofile/index/somestring.
YOu seem to be skipping the action part.

How does ASP.Net MVC ActionLink Work?

I am trying to write my own LightWeight MVC for .Net 2.0 using NHaml as the view engine.
In ASP.Net 3.5 MVC the View file we used to specify the link by the code snippet.
Html.ActionLink("Add Product","Add");
In MVC binary there is no function to match this call.
I Only found:
(In class System.Web.Mvc.Html.LinkExtensions )
public static string ActionLink(this System.Web.Mvc.HtmlHelper htmlHelper,
string linkText, string actionName)
There are more similar static classes like FormExtensions, InputExtensions etc.
How does ASP.Net MVC handle it? Does it generates dynamic code for Html.ActionLink?
The ActionLink method is an extension method (hence the this before the type of the first parameter). This means you can use this method as an instance method on all HtmlHelper instances, even though it is not defined on HtmlHelper.
Html is a property on the View of type HtmlHelper. This means you can use the ActionLink extensionmethod on it.
The ActionLink method itself does nothing more than generate a link string (with regards to its arguments) and return that string.
Have you checked out the code on Codeplex? The MVC Framwork is open source, so you can dig around as much as you need to.

Resources