Search in Help for developer site.

Tuesday 31 October 2017

Implement custom helper methods in ASP.NET MVC

Overview :

In the world of MVC web development , you might have built various rich UI web application by using HTML user interface components say textbox, checkbox,dropdown etc.

Most of the time while designing your UI, you might have used normal HTML controls or built-in MVC helper methods.. isn't it?. but there may be a situation where MVC built-in helper methods or conventional HTML controls will not full fill your requirements. i.e., at times you may want to load dropdown items based on some condition or logic.

So to overcome this situation, we will be using custom helper methods using which we can formulate the data by adding business logic of our own.

Well, today I am going to explain how to create custom dropdown helper method in MVC.


Step 1 : Create a MVC app using VS tool.

Step 2 : Add Controller , name it as 'Home'. And create action method , name it as 'Index'.

Step 3 : Create view for Index action method.

I have added following code inside the view.

@using CustomHelperMethod
<br />
 &nbsp;<span style="font-weight:bold">Add Student Form</span>
<hr />
<table>
    <tr>
        <td>
            Name :
        </td>
        <td>
            @Html.TextBox("studentName")
        </td>
    </tr>
    <tr>
        <td>
            Gender :
        </td>
        <td>
            @Html.CustomGenderDropDownList("studentGender", "--Select--")
        </td>
    </tr>
</table>
<hr />
<footer>
    <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>

</footer>

As you can observe above lines of code., I have created simple student form where  I have added a custom dropdown control 

 "@Html.CustomGenderDropDownList("studentGender","--Select--")".

MVC does not have this type of helper method in its assembly. It is an extension method. 
Now run the application and check the result.


 

As you can see above picture, I am able to load gender dropdown items using custom dropdown helper method.
Follow below steps to implement custom dropdown helper method.

Step 1 : Create a class and name it as you like.

Step 2 : Add below line of code inside it.





using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

namespace CustomHelperMethod
{
    public static class HelperMethod
    {
        public static MvcHtmlString CustomGenderDropDownList(this HtmlHelper helper, string controlName,
                       string optionalLabel = "", object htmlAttributes = null)
        {

            IEnumerable<SelectListItem> selectList = null;
            List<SelectListItem> genderList = new List<SelectListItem>();
            genderList.Add(new SelectListItem() { Text = "Male", Value = "1" });
            genderList.Add(new SelectListItem() { Text = "Female", Value = "2" });
            selectList = (IEnumerable<SelectListItem>)new SelectList(genderList, "Value", "Text");
            if (htmlAttributes != null && htmlAttributes is RouteValueDictionary)
            {
                RouteValueDictionary htmlAttr = htmlAttributes as RouteValueDictionary;
                if (!string.IsNullOrEmpty(optionalLabel))
                    return helper.DropDownList(controlName, selectList, optionalLabel, htmlAttr);
                else
                    return helper.DropDownList(controlName, selectList, htmlAttr);
            }
            if (!string.IsNullOrEmpty(optionalLabel))
                return helper.DropDownList(controlName, selectList, optionalLabel, htmlAttributes);
            else
                return helper.DropDownList(controlName, selectList, htmlAttributes);
        }
    }
}
 
As you can have a look at above,
I have written a method called 'CustomGenderDropDownList' which is expecting multiple parameters such as name, optional label and html attributes.

Here ,
1. 'name' parameter indicates control's name
2. 'Optional Label' indicates whether or not you want to display '--select--' as first item in your dropdown control.

 I added sample list of items and added them into IEnumerable of SelectListItem object
and pass them to 'helper.DropdownList' method and return it as . MvcHtmlString object.

Note: You can pull object list from DB and add them to 'IEnumerable of SelectListItem' object

That's it. You are done.

Note :

1. If you would like to add strongly typed dropdown control , write a helper method as below

public static MvcHtmlString CustomGenderDropDownListFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string optionalLabel, object htmlAttributes = null)
{
    --Add your logic--
}
Thank you.

Please feel free to ask your querries. I will be glad to help you all. And Hope this article will help you guys.


 User reads below articles also:

 The Various Ways of Binding MVC DropDownList

How to Disable Required Attribute for Value Types in MVC





Saturday 21 October 2017

How to create custom code snippets in visual studio

Custom Code Snippets in Visual Studio.

Today i'm going to share a very useful feature of visual studio. Code snippet is a great inbuilt feature of visual studio and we are already familiar with code snippets. We are using them in our daily programming life.

Some inbuilt code snippets for C#:-
  • Prop:- to create a property
  • Ctor:-  to create a class constructor.
  • foreach:- to create a foreach loop
  • so on....
Do you know we can create our own code snippet like above snippets.

See also : ajax pagination and sorting in asp net mvc webgrid

Create custom code snippets in visual studio

We will create a custom code snippet for ASP.NET MVC action method with try catch block.
And will name it as actionMethod.
When we use this actionMethod snippet, It should insert a code as below.
        public ActionResult ActionMethodName()
        {
            try
            {
                //Do some work
            }
            catch (Exception ex)
            {
                throw;
            }
            return View();
    }

Step 1: Create a new project in visual studio and select asp.net application and name it as CustomCodeSnippets, click ok, then select empty project.
because we just need to create a xml file with .snippet file extenstion.


Step 2: After that add a new xml file and name it as actionMethod.snippet


Note: .snippet extension is mandatory to create a snippet file.

After adding this actionMethod.snippet xml file you will see the file as below.

<?xml version="1.0" encoding="utf-8" ?>

Now right click in recently added file and click on Insert Snippet option.

After that it will show snippet options. In that click on Snippet option.

It will insert a code to create our own code snippets as below.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>title</Title>
    <Author>author</Author>
    <Shortcut>shortcut</Shortcut>
    <Description>description</Description>
    <SnippetTypes>
      <SnippetType>SurroundsWith</SnippetType>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>name</ID>
        <Default>value</Default>
      </Literal>
    </Declarations>
    <Code Language="XML">
      <![CDATA[<test>
      <name>$name$</name>
      $selected$ $end$</test>]]>
    </Code>
  </Snippet>
</CodeSnippet>

So in the above code you can understand it by their tag name. They are self described like Title, Author, Shortcut, Description etc.
 In the Code tag we will insert our code.
So now modify the above code as below.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>Action Method Code Snippet</Title>
    <Author>HelpForDeveloper</Author>
    <Shortcut>actionmethod</Shortcut>
    <Description>Inserts a code snippets for ASP.NET MVC Action Method</Description>
    <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Declarations>
      <Literal>
        <ID>ActionMethodName</ID>
        <Default>ActionMethodName</Default>
      </Literal>
    </Declarations>
    <Code Language="CSharp">
      <![CDATA[
      public ActionResult $ActionMethodName$()
        {
            try
            {
                //Do some work
            }
            catch (Exception ex)
            {
                throw;
            }
            return View();
        }
      ]]>
    </Code>
  </Snippet>
</CodeSnippet>

Here we mentioned "actionMethod" as our shortcut.

Step 3: Importing actionMethod.snippet file to Code Snippet Manager to make it available globally.

Go to Tools->Code Snippet Manager


Click on Import and Locate that file, Once you locate that click Ok.
Then do as below.

Now click on finish and your custom code snippet will be copied at this location. "C:\Users\sushil\Documents\Visual Studio 2015\Code Snippets\Visual C#\My Code Snippets"

Our code snippet is ready to use.
To use that create a new ASP.NET MVC project and in the controller file type our code snippet shortcut as "actionmethod"



Visual Studio Intelligence is giving suggestion for our own code snippet. Now click the tab twice and your ready made action method with try catch block shall be inserted as below.

   public ActionResult ActionMethodName()
        {
            try
            {
                //Do some work
            }
            catch (Exception ex)
            {
                throw;
            }
            return View();
        }

Summary:- 
We have seen how to create our own code snippet and how to use them. You can customize it based on your requirement.

Tips: While developing a web application if you notice that you are writing a particular code block again and again then it the right choice for your new custom code snippet. 

Users also read these articles:

Tool to generate C# Model Class or Data Object of a Database Table

Difficulties facing in jquery Ajax call and handling it to get proper response from server side code(MVC)


Thanks for reading.
If you have any doubt please put your comments in the comment section.