Tag Archives: ASP.NET

C#- Creating Custom HTML Helpers – Full Example

Custom HTML Helpers can help seperation of code and html and avoid repetion.

What is a HTML Helper ?

It is just a method that will return a string which can contain any content you wan from a simple string to a table of data.

Why are HTML Helpers useful ?

method that returns a string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input> and <img> tags. In ASP.NET we have many standard HTML Helpers

  • Html.ActionLink()
  • Html.BeginForm()
  • Html.CheckBox()
  • Html.DropDownList()
  • Html.EndForm()
  • Html.Hidden()
  • Html.ListBox()
  • Html.Password()
  • Html.RadioButton()
  • Html.TextArea()
  • Html.TextBox()

 

 

Let us think of a situation.

In a  web page we need to list the features of a product.

If the feature is present then show a Tick

If the feature is missing then show a Cross

As shown below.

 

 

Capture

 

 

This is achieved by using two different CSS classes which will render the Tick or the Cross

When I use my CSS class “plain” it will render a Cross

When I use the class “checked” it shows a Tick.

Capture2

 

 

Now in razor view you would typically use the

@Html.DisplayFor(model => model.Alarm)   which would render a standard check box ( if true then the checkbox will be ticked and if false the checkbox will be empty) But we want a better display hence we want to make use of our CSS classes.

In order to show the customised CSS we will have to write some logic in the Razor view which is not preferred at all as we would like to keep the logic out from the views and secondly it will need a lot of code as for each item we will have to use some kind of If loop as shown below.

 

Not recommended

@if (Model.AirConditioning == true)
{
<li class=”ticked”>@Html.LabelFor(model => model.AirConditioning)</li> }
else
{
<li class=”plain”>@Html.LabelFor(model => model.AirConditioning)</li> }

 

 

Better Alternative is to write a Custom HTMLHelper

Let us write a Custom HTML Helper for it.

 

Create a Class

I created a folder called HTMLHelpers in my project and then created a class called myHTMLHelpers.cs as shown below

Capture3

The content of the class is as below

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace myapplication.Helpers
{
    public static class myHTMLHelpers
    {


    
          public static IHtmlString TickOrCross(bool content)
            {
                string htmlString = "";
              
         
                if(content==true)
                    {
                        htmlString = String.Format("checked");  // if content is true then we want the CSS class checked

                    }
                    else
                    {

                        htmlString = String.Format("plain"); // if content is falsethen we want the CSS class plain
                    }

                return new HtmlString(htmlString);

            }
          }
    }

How te make use of this HTML Helper ?

Go to your Razor View

 

at the top of the page add the namespace under which we created our helper class

@using myapplication.Helpers

 

 

at the right place in your razor view I have  made use of our custom html helper.

We pass the model value to it and it will set the class name accordingly to display a Tick or a Cross

                                    <ul class=”span2″>
<li class=”@myHTMLHelpers.TickOrCross(Model.AirConditioning)“>Air Conditioning</li>
<li class=”@myHTMLHelpers.TickOrCross(Model.Alarm)“>Alarm</li>

</ul>

The other way would have been to put the logic into the view using the if block in our code,. which is not a good practice.

@if (Model.AirConditioning == true)
{
<li class=”ticked”>Air Conditioning</li> }
else
{
<li class=”plain”>Air Conditioning</li>
}

How to render @html.actionlink as a button in MVC in Razor

How to render  @HTML.Actionlink  in MVC and using it as a button

Background of @HTML.ACTIONLINK in MVC

The easiest way to render an HTML link in is to use the HTML.ActionLink() helper.

With MVC, the Html.ActionLink() does not link to a view. It creates a link to a controller action.

Razor Syntax:

@Html.ActionLink(“About this Website”, “About”)

ASP Syntax:

<%=Html.ActionLink(“About this Website”, “About”)%>

The first parameter is the link text, and the second parameter is the name of the controller action.

The Html.ActionLink() helper above, outputs the following HTML:

<a href=”/Home/About”>About this Website</a>

 

 

When using  @html.actionlink it normally renders it like a hyperlink. But there is a simple way to render it as a button.

 

Simple example of  @HTML.Actionlink

@Html.ActionLink("Register,"Register")

 

and it will render it as a  Hyperlink

 

 

How to render  @HTML.Actionlink as a button

 

I am using Boostrap so I have the CSS class called “btn” available. Otherwise you can use your own CSS which can create a button

 

 Here is your Answer below

C# Syntax

@Html.ActionLink("Register", "Register" ,null,  new { @class = "btn" })

 

VB.NET Syntax

@Html.ActionLink("Register", "Register" ,null,  new  with {.class = "btn" })   



the null is for the Routevalues ( in the example we are using any route values hence null)

 

Hope this helps you

VB.NET – You must call the “WebSecurity.InitializeDatabaseConnection” method before you call any other method of the “WebSecurity” class.

Problem description:

If you are getting the error while running your MVC4 application in VB.NET

You must call the “WebSecurity.InitializeDatabaseConnection” method before you call any other method of the “WebSecurity” class.

Solution

Add the following line in the GLOBAL.ASX

Capture

 

Ensure that you are using the correct connection string and other information as per your own application as  shown in the highlighted line above.

Role based Authorization in MVC4 using VB.NET

Here is a simple way to do the role based Authorization in your MVC4 Controllers using VB.NET

IF you have a role called Client then simply add the following text on top of your each ActionResult( which displays the view)

<Authorize(Roles:=”Client”)>

 

See the following example. The Index View has been restricted and can only be viewed by someone in the Client role.

 <Authorize(Roles:="Client")>
        Function Index() As ActionResult
            Return View(db.Purchasers.ToList())
        End Function

Password protect complete MVC4 site in VB.NET

If you want to password protect some pages on your MVC4 site using the Forms Authentication then it is best to to protect the whole site and then selectively allow Anonymous Access to the pages which are to be shown to every visitor.
authentication in MVC4

Open the FilterConfig.VB file and add the line

filters.Add(New AuthorizeAttribute)   in it

 

Once you run your application you would see that all the pages of your website are now protected, the users have to register before they can access.

 

Imports System.Web
 Imports System.Web.Mvc
Public Class FilterConfig
 Public Shared Sub RegisterGlobalFilters(ByVal filters As GlobalFilterCollection)
 filters.Add(New HandleErrorAttribute())
 filters.Add(New AuthorizeAttribute)
 End Sub
 End Class

 

If you need to allow some pages for anonymous view then add the following decoration.

<AllowAnonymouse()> on each page which you want to open up for anonymous access.

 

    <AllowAnonymous()>
    Function Index() As ActionResult
        ViewData("Message") = "Modify this template to jump-start your ASP.NET MVC application."
        Dim rep As New RepositoryRealEstate

        ViewBag.AgentCount = rep.GetAgentsCount
        ViewBag.ProperyCount = rep.GetPropertyCount
        ViewBag.VendorCount = rep.getvendorcount
        Return View()
    End Function

A potentially dangerous Request.Form value was detected from the client – error in MVC4 in vb.net

In your Create Actions in a Controller in MVC4, if you try to save text with html tags then you get this annoying error.

A potentially dangerous Request.Form value was detected from the client

Description: ASP.NET has detected data in the request that is potentially dangerous because it might include HTML markup or script. The data might represent an attempt to compromise the security of your application, such as a cross-site scripting attack. If this type of input is appropriate in your application, you can include code in a web page to explicitly allow it. For more information, see http://go.microsoft.com/fwlink/?LinkID=212874.

This is a great protection if you do not want your client to save html text.

Here is how to get rid of this error

In the following example we have a create action which saves a new record. MVC4 controller will have two functions.

The first function is for GET ( this is the one which will render the page to save the new record

 

The second function is for POST. This function is responsible to receive the model
which has been populated by the data which the user has filled in on the form. We have to add the following text

<ValidateInput(False)>

 

for C# add

[ValidateInput(false)]

 

 

 

 

‘ GET: /admin/ManageAds/Create

Function Create() As ActionResult
Return View()
End Function

 

 

‘ POST: /admin/ManageAds/Create
<HttpPost()> _
<ValidateAntiForgeryToken()> _
<ValidateInput(False)>
Function Create(ByVal ad As Ad) As ActionResult
If ModelState.IsValid Then
db.Ads.Add(ad)
db.SaveChanges()
Return RedirectToAction(“Index”)
End If

Return View(ad)
End Function

 

How to download a file in MVC4 using VB.NET

How to allow File Downloads in MVC4 using VB.NET

We are using an ActionResult instead of FileResult.

Function download(id as Integer) As ActionResult

The reason is that if use the FileResult and your file does not exist then it will show a blank page, instead of this

we are using an ActionResult which is more versatile.
We can return the actual FileResult if the file exists
and in case of an error we can return a View (if we used a FileResult

Function download(id as Integer) As ActionResult

‘ In this example we are using the id to pick up the actual file from a model

Dim SoundFile as SoundFile = db.SoundFiles.Find(id)

Dim path As String = Server.MapPath(“~/myLocation/” & SoundFile.MP3File)

‘get file object as FileInfo
Dim fileinfo As System.IO.FileInfo = New System.IO.FileInfo(path)

‘– if the file exists on the server

If fileinfo.Exists Then
rep.IncrementDownloadCount(id) ‘This is my routine to count the downloads, you will not need it
Return File(path, “application/octet-stream”, fileinfo.Name)
Else
Return View(“Error”)
End If

End Function

How to use Nested MaserPages in VB.Net websites

Well here is a situation.

I create 3 templates and each one of them will have a MasterPage. Eg. TemplateMaster1, TemplateMaster2 and TemplateMaster3

Then I create another MasterPage called SiteMasterPage

and in SiteMaster I call one of the three templates ( eg. TemplateMaster1)

Then I create a default.aspx page which will refer to the SiteMasterPage

Now the <asp:ContentPlaceHolder> tags which are in TemplateMaster1 can not be directly used in my default.aspx page

In order to use them here is a work around

Whereever you want to put the custom content.

Create a  <asp:Content> tag in  your SiteMasterPage first and then within it create a <asp:ContentPlaceHolder> tag

Here is an example.

<asp:Content ID=”Main”  ContentPlaceHolderID=”TemplateMain” runat=”server”>
<asp:ContentPlaceHolder ID=”MasterMain” runat=”server”>

</asp:ContentPlaceHolder>

</asp:Content>

Then in your default.aspx page you can place the MasterMain

<asp:Content Id=”Main” ContentPlaceHolderID =MasterMain runat=”server”>

<h1>Welcome to this content  which is using nested masterpages</h1>

</asp:Content>

Select and edit a record in GridView in vb.net

If you want to select a record in a Gridview in VB.Net and then edit that record in a separate page, then you can use the following code to give you an idea.

I assume that you alredy know how to add a gridview and populate it using vb.net

You would need to add a hyperlink field in the gridview columns as shown belo

The headertext will show what will appear in the header row
datatextfield will be name of your datafield which is the primary key for the data
datanavigateurlformatstring  – this field will construct the name of your page which the system will navigate to if someone clicks on the edit button
datanavigateurlfields  is again the primary key eg. My primary key was “NewsId”
DataTextFormatString  tells what will be displayed on the data gridl eg. I want to show a hyperlink called “Edit”

so whenever someone clicks on the edit button the system will take you to the “EditNews.aspx?q=1 where 1 will be the NewsID

<asp:hyperlinkfield headertext=”Edit” datatextfield=”NewsID” datanavigateurlformatstring=”EditNews.aspx?q={0}” datanavigateurlfields=”NewsID” DataTextFormatString=”Edit” Text=”Edit” />

Here is the complete code which shows where the hyperlink code will sit

<asp:GridView ID=”GridView1″ runat=”server” AllowPaging=”True”
AllowSorting=”True” AutoGenerateColumns=”False” DataKeyNames=”NewsID”
DataSourceID=”SqlDataNews” Width=”617px”>

<Columns>
<asp:BoundField DataField=”NewsID” HeaderText=”NewsID” InsertVisible=”False”
ReadOnly=”True” SortExpression=”NewsID” />

<asp:BoundField DataField=”NewsDate” HeaderText=”NewsDate”
SortExpression=”NewsDate” />
<asp:BoundField DataField=”NewsStartDate” HeaderText=”NewsStartDate”
SortExpression=”NewsStartDate” />
<asp:BoundField DataField=”NewsEndDate” HeaderText=”NewsEndDate”
SortExpression=”NewsEndDate” />
<asp:BoundField DataField=”NewsShortDescripton”
HeaderText=”NewsShortDescripton” SortExpression=”NewsShortDescripton” />

<asp:hyperlinkfield headertext=”Edit”
datatextfield=”NewsID”

datanavigateurlformatstring=”EditNews.aspx?q={0}”
datanavigateurlfields=”NewsID” DataTextFormatString=”Edit” Text=”Edit” />

</Columns>

</asp:GridView>