Asp.net MVC HtmlHelper and UrlHelper

<% using (Html.BeginForm()) { %>

<% using (Html.BeginForm()) { %>

 

HtmlHelper class vs. UrlHelper class

HtmlHelper is to emit out entire html tags, like Html.BeginForm() will output something like

<form action="/blog/setting/password" method="post">

Whereas UrlHelper will only output an url,

Both can be extended using Extension Methods, for example I created my own class UrlHelperExtension,

public static class UrlHelperExtension
{
public static string Home(this UrlHelper helper)
{
return helper.Content("~/");
}
}

When using it you can,

<a href="<%= Url.BlogHome() %>">Blog</a>

 

HtmlHelper

When you don’t specify anything in the BeginForm,

<% using (Html.BeginForm()) { %>

 

the action attribute will have value of whatever path this .aspx page’s url has

<form action="/blog/setting/password" method="post">

 

Alternatively, you can do

<form id="changePasswordForm" action="<%= Url.Action("ChangePassword", "Account") %>" method="post">

 
 
 

Define URL Flow

1. Global.asax
routes.MapRoute("SettingGeneral", "setting/general", 
new { controller = "Default", action = "SettingGeneral" });

2. UrlExtensions.cs

public static string SettingGeneral(this UrlHelper helper)
{
return helper.RouteUrl("SettingGeneral");
}

3. The view: aspx, ascx

<a href="<%= Url.SettingGeneral() %>">Setting</a><br />

Advertisements