Learning {{AngularJS}} with ASP.NET MVC – Part 3


This post is third part in the series on AngularJS. In first part, we created a simple Hello World application using AngularJS and in second part, we created a page which displays data in tabular format and used some directives to generate that. We also discussed one of the very important components, Module and provided a proper structure to our application. Please find the link of my earlier posts below

Learning {{AngularJS}} with Examples–Part 1

Learning {{AngularJS}} with Examples–Part 2

Let’s see that in last two post what have we covered and what will we be discussing today.

Structure

So we have covered three components in our earlier posts and will be using two more components in today’s post as in the above image.

Continue reading

Advertisements

Exploring Enums support in ASP.NET MVC 5.1 – Part 2

This is second part of the series of exploring enums support in ASP.NET MVC 5.1 that was recently got released with Visual Studio 2013 Update 2. The first part of the series can be read from the below link

Enums support in ASP.NET MVC 5.1- Part 1

In last post we discussed that how the new scaffolding works fantastic for enum types as well. But there are other different scenarios where we need to customize it before displaying on UI. We discuss the issue in one of the sceanio in last post. To handle these scenarios, few other new helper methods got introduced. A new class EnumHelper got added which has two methods :

GetSelectList – which has four overridden method and it returns a list of SelectListItem which can be used to further populate the dropdown in UI.

IsValidForEnumHelper– This method also has two overridden method that tells whether the passed type is enum. This should be used to check the type of passed value and GetSelectList should be used if IsValidForEnumHelper returns true.

So let’s jump to the example and use the above methods.

In part-1 of the series, we used the following enum in the example

public enum ExpertiseArea
{
    ASPNET,
    Csharp,
    WindowsAzure,
    WCF
}

but as we know that enum properties can not include space or some special characters. Say, if we want to display WindowsAzure as Windows Azure or ASPNET as ASP.NET etc. In this scenario, we need to create custom views for edit and display purposes.

First let’s change the enum itself and add the display attributes as

    public enum ExpertiseArea
    {
        [Display(Name = "ASP.NET")]
        ASPNET,
        [Display(Name = "C#")]
        Csharp,
        [Display(Name = "Windows Azure")]
        WindowsAzure,
        WCF
    }

Now let’s create the partial view for display scenario.  Here we need to cater multiple scenarios like

– If there are some items which has some selected value for enum property then find the selected text/vale. SelectedText represent the display attribute

– If nothing is selected then show the empty value. (Empty value cannot be converted in enum type)

– If the type itself is not an enum then use the normal value.

We can write it as

@model Enum

@if (EnumHelper.IsValidForEnumHelper(ViewData.ModelMetadata))
{
    string displayAttrName = null;
    foreach (SelectListItem item in EnumHelper.GetSelectList(ViewData.ModelMetadata, (Enum)Model))
    {
        if (item.Selected)
        {
            displayAttrName = item.Text ?? item.Value;
        }
    }

    // displayAttrName is not assigned to any value
    if (String.IsNullOrEmpty(displayAttrName))
    {
        if (Model == null)
        {
            displayAttrName = String.Empty;
        }
        else
        {
            displayAttrName = Model.ToString();
        }
    }

    @Html.DisplayTextFor(model => displayAttrName)
}
else
{
    @Html.DisplayTextFor(model => model)
}

Make sure that above Partial View enum.cshtml is created in EditorTemplates folder under the Shared directory.

So if we see the above code, then we find that EnumHelper.IsValidForEnumHelper is used to check that whether the passed value is of enum type and the other one EnumHelper.GetSelectList which returns the list of items in SelectListItem type as discussed.

Now let’s us create the partial view for Edit purposes as

@model Enum

@if (EnumHelper.IsValidForEnumHelper(ViewData.ModelMetadata))
{
    @Html.EnumDropDownListFor(model => model, htmlAttributes: new { @class = "form-control" })
}
else
{
    @Html.TextBoxFor(model => model, htmlAttributes: new { @class = "form-control" })
}

This partial view also should be in EditorTemplates folder under the Shared directory. Here again the new helper method EnumHelper.IsValidForEnumHelper which tells whether the provided model data is of type enum or not. When it is of type enum then it uses @Html.EnumDropDownListFor else uses normal @Html.TextBoxFor

Now let’s see the Create/Edit views and here we have not used
@Html.EnumDropDownListFor instead used normal @Html.EditorFor which uses the display and edit templates that we created

   @Html.EditorFor(model => model.Area)

Now let’s run the application, in create page looks like

Part2-1

and after adding Index look as

part2-2Here the earlier issue is resolved and we are able to see the consistent values on diffrent CRUD screen. We can write the similar custom code in other scenarios as well.

Happy learning,
Brij

Enums support in ASP.NET MVC 5.1- Part 1

Hello All,

Recently Microsoft releases a second update for Visual Studio 2013 named Visual Studio Update 2 RC. Here RC means that it is in Release candidate version  and you may expect few changes in the final version. But there are a list of changes they provided in ASP.NET MVC and Webforms that will be going to help a lot in your day to day coding. The new version of ASP.NET MVC is named as ASP.NET MVC5.1. In few of my coming posts, I’ll be discussing the major changes in ASP.NET MVC with examples.

So in this post, We’ll discuss few features of ASP.NET MVC5.1. ASP.NET MVC provides scaffolding that enables us to create the controller and views for our model. The controls on views are rendered based on the type of properties in the model but it is not true for all types. Say if you have property in your which is of type Enum then the UI generate the normal textbox for it which allows to enter free text which may become brutal to your application if it is not handled properly. To handle this scenario, I discuss that in one my old post, how you can extend EditorFor for custom type. You can refer the link

Html.EditorFor – Extend for custom type

But it requires lots of steps and require to handle various scenarios like displaying, editing etc which is error prone as well. Let’s take the same earlier example, I took a class as

    public class Speaker
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public bool IsAvailable { get; set; }

        public ExpertiseArea Area { get; set; }
    }

The enum type ExpertiseArea is defined as

    public enum ExpertiseArea
    {
        ASPNET,
        Csharp,
        WindowsAzure,
        WCF
    }

Now when I created the Controller and Views via scaffolding as

Controller

and

addcontroller

and It created the controller and related views. Now lets run the application so it looks like as

page

Great!! Now you can see that expertise area is rendered as dropdown without any specific code. That’s fantastic.

Now let’s have a look on the cshtml page itself

 @Html.EnumDropDownListFor(model => model.Area, htmlAttributes: new { @class = "form-control" })

So here, we find that there is a new helper method EnumDropDownListFor got introduced that is used for enum types. And this is used for on Create and Edit views because these views only allows user to edit or enter new data. Rest of the views are same as earlier.

This is very good feature that will help a lot to developers.For simple scenario it is fine, so let us discuss another scenario, where we dont want to show the actual enum value but we want to show some different value on the UI. So let’s add display attribute in enum as

    public enum ExpertiseArea
    {
        [Display(Name = "ASP.NET")]
        ASPNET,
        [Display(Name = "C#")]
        Csharp,
        [Display(Name = "Windows Azure")]
        WindowsAzure,
        WCF
    }

Now again, let’s run the application and see the create page

part1-1It seems great, the value that populated in dropdown is what we put in display attribute. That’s what we want. Let’s add it and see the index page

part1-2Ohh.. this we did not expect. We expected that it should be C#. It means that it cannot be handled without just by simple scaffolding but it is required some custom code.

We’ll discuss this scenario in next part. Stay tuned!

Cheers,
Brij

Speaking on ASP.NET MVC5 at C# Corner Annual Conference 2014 – Apr 12

Hello All,

csharpcornerI am very excited to share you all that I’ll be speaking in C# Corner Annual Conference 2014. C# Corner Annual Conference is North India’s largest conference and hosted by http://www.c-sharpcorner.com/ from last four years.

It is a full day event and you’ll get ample opportunity to learn from renowned International/national speakers. For more details Click here

I’ll be speaking on the latest version of ASP.NET MVC (5) and discuss how it solves your real time issues and make our life easier. The agenda of my session will be

  • One ASP.NET
  • Know the power of Attribute routing
  • Authentication using external authentication providers
  • Build the rich and clean UI with Bootstrap
  • Using Authentication filters
  • Lots of demos

You’ll enjoy the day with lot of learnings and fun. See you all there..

Cheers,
Brij

 

Html.EditorFor – Extend for custom type

In this Post, I am going to discuss about ASP.NET MVC and razor view engine. As we know that ASP.NET MVC provides many helper methods that helps in generating the UI based on the model. But there could be scenario where the available HTML helpers wont work and you require to create new custom one. There could be one scenario, where you have a class that has a enum property. Now if you create a Create/Edit view for that property then it will just create a TextBox for it. Obviously which is not a good idea. A User may enter some wrong string which cannot mapped to a enum value. So the better way to provide a dropdown to select any value. There could be many ways to render it. We’ll discuss one elegant way to do this.

First let’s understand that how does the available helpers work. Lets start with an example. Say we have a class like

    public class Speaker
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public bool IsAvailable { get; set; }
    }

So here, in this class there are three properties: Id, Name and IsAvaiable. The first two are of type string and third one is of bool. So when we create a View for this model It looks like

</pre>
<div class="editor-field">@Html.EditorFor(model => model.Name)
 @Html.ValidationMessageFor(model => model.Name)</div>
<div class="editor-field">@Html.EditorFor(model => model.IsAvailable)
 @Html.ValidationMessageFor(model => model.IsAvailable)</div>
<pre>

I have not included the whole source code of the View but if we see the above code then find an EditorFor (called templated helper) is used to generate the UI. Let’s run and see the UI Initial We can see one Textbox and other Checkbox on the screen right. But how does it take place? Actually when it renders on the browser, it checks the type of the property, and based on the type, picks the appropriate template and renders it on screen. For type string(which is name here), it has a defined template as Textbox and for bool (which is here IsAvailable) also it has a template as Checkbox . So the same templated editor method renders different UI based on the type of the property. Let’s move ahead and add another enum property I have created a enum type as

 public enum ExpertiseArea
    {
        ASPNET,
        Csharp,
        WindowsAzure,
        WCF
    }

Now lets add one more property to the class of type enum defined as above

public ExpertiseArea Area { get; set; }

Now we need to add a new editor for Area as

</pre>
<div class="editor-field">@Html.EditorFor(model => model.Area)
 @Html.ValidationMessageFor(model => model.Area)</div>
<pre>

When it will be rendered on UI, it will simply add a Textbox for enum as

withoutddl

which is not a good Idea as discussed. To provide a Dropdownlist for the enum, we need to create a custom editor template.

To create a custom editor template, create a folder named EditorTemplates under Views->Shared folder. So that the editor templates gets available to all the Views.Now create a Partial View under that folder with name as your Enum (which is here ExpertiseArea so partial view file name will be ExpertiseArea.cshtml). Now in this View we need to create the drop down list. For dropdown list, we need to get all the item names from the Enum Type and create the items for drop down. So here my my partial view ExpertiseArea.cshtml contains

@using System.Web.Mvc;
@using Application1.Models;
@{
    var names = Enum.GetNames(typeof(ExpertiseArea));
    var values = Enum.GetValues(typeof(ExpertiseArea)).Cast();

    var items = names.Zip(values, (name, value) =>
        new SelectListItem { Text = name, Value = value.ToString() });
}

@Html.DropDownList("", items)

In above code, We are getting all the names and values from Enum and creating the items for dropdown and once we create the items, we used the dropdown list helper to populate the dropdown. So now lets render the create the page again.

dropdownNow a dropdown is rendered with all the possible enum type values for enum type property. And the same will be used at many places, wherever we want to get the user input on this enum value. And there will be no change in the Views.

So we have seen that how easily we can create custom editors for specifc types and can use it uni formally in the entire application.

Happy Learning,
Brij

Join ‘Hands on Lab’ on ASP.NET MVC and Entity Framework with me

Hello All,

C# Corner Delhi Chapter is going to organize first event of the new year on 18th January 2014. It will be a full day event and a list of hot technologies will be discussed throughout the day.  The whole day will include two hand on labs one on ASP.NET MVC5 and other on WCF Services. Agenda of the day will be

  • Expose CRUD Operation as WCF Services (HOL) by Dhananjay Kumar
  • Get hand on Threading in C-Sharp by Suchit Khanna
  • Learn to do Unit Testing of your code using NUnit by Amit Chaudhary
  • CRUD Operation on ASP.NET MVC (HOL) by Brij Mishra

The details of the event are

Date and Timing – 18th Jan 2014, 10:30 PM to 5:00 PM

Is there any fee – No. It is Absolutely free

Venue –

MCN Solutions Pvt. Ltd.
H-217, Second Floor,
Sector-63, Noida
Landmark: Behind Indian-Oil Petrol Pump
Contact No: +91-9810371053

I’ll cover the following topics in my Hands on lab

  •     Introduction to ASP.NET MVC and ASP.NET MVC5
  •     Create MVC App performing CRUD
  •     Create model using Entity Framework
  •     Authentication using external Identity Providers

For more details and registration Click here

Come with your friend and learn with us. See you all at the event.
Cheers,
Brij

WebGrease : A fantastic tool for Web Optimization

In this post, We are going to talk a library that you guys must have seen in latest version of ASP.NET (4.5) and ASP.NET MVC (4.0). So first let’s first understand,

What is WebGrease?

WebGrease is a suit of tools that helps is optimizing the static files (like JavaScript, CSS) in a web application. This tool is developed by a performance team in MSN division of Microsoft . Actually It is evolution of the AJAX min library that we are already using.  This team continuously works on the optimization of their web sites. So the current capabilities of WebGrease are

Continue reading