Monday, March 16, 2015

ASP.NET MVC: Quick Reference for Beginners

  1. Installing ASP.NET MVC
  2. What asp.net mvc version is my mvc application using
  3. Creating your first asp.net mvc application
  4. Controllers in an mvc application
  5. Views in an mvc application
  6. ViewData and ViewBag in mvc
  7. Models in an mvc application
  8. Data access in MVC using entity framework
  9. Generate hyperlinks using actionlink html helper
  10. Working with multiple tables in mvc
  11. Using business objects as model in MVC
  12. Creating a view to insert data
  13. FormCollection in MVC
  14. Mapping asp.net request data to controller action simple parameter types
  15. Updatemodel function in MVC
  16. Difference between updatemodel and tryupdatemodel
  17. Editing a model in mvc
  18. Updating data in MVC
  19. Unintended updates in mvc
  20. Preventing unintended updates
  21. Including and excluding properties from model binding using bind attribute
  22. Including and excluding properties from model binding using interfaces
  23. Why deleting database records using get request is bad
  24. Deleting database records using post request in mvc
  25. Insert update delete in mvc using entity framework
  26. Customizing the auto-generated index view
  27. Customizing the autogenerated create view
  28. Customizing the autogenerated edit view
  29. Using data transfer object as the model in mvc
  30. View engines in asp.net mvc
  31. Using custom view engines with asp.net mvc
  32. How does a controller find a view
  33. Html helpers in MVC
  34. Generating a dropdownlist control in mvc using HTML helpers
  35. How to set an item selected when dropdownlist is loaded
  36. Difference between Html.TextBox and Html.TextBoxFor
  37. Generating a radiobuttonlist control in mvc using HTML helpers
  38. CheckBoxList in asp.net mvc
  39. ListBox in asp.net mvc
  40. Using displayname, displayformat, scaffoldcolumn attributes in mvc
  41. Using datatype & displaycolumn attributes
  42. Opening a page in new browser window
  43. Hiddeninput and readonly attributes in mvc
  44. Display and edit templated helpers
  45. Customize display and edit templates
  46. Accessing model metadata from custom templated helpers
  47. Displaying images in asp.net mvc
  48. Custom html helpers in mvc
  49. Html encoding in asp.net mvc
  50. Detect errors in views at compile time
  51. Advantages of using strongly typed views
  52. Partial views
  53. Difference between html.partial and html.renderpartial
  54. T4 templates in asp.net mvc
  55. What is cross site scripting attack
  56. How to prevent cross site scripting attack
  57. Razor views in mvc
  58. Razor views in mvc continued
  59. Layout view in mvc
  60. ViewStart in asp.net mvc
  61. Named sections in layout files in mvc
  62. Implementing search functionality in asp.net mvc
  63. Implement paging in asp.net mvc
  64. Implement sorting in asp.net mvc
  65. Deleting multiple rows
  66. Check uncheck all checkboxes with another single checkbox using jquery
  67. Action selectors in mvc
  68. What is the use of NonAction attribute in mvc
  69. Action filters in mvc
  70. Authorize and AllowAnonymous action filters
  71. ChildActionOnly attribute in mvc
  72. HandleError attribute
  73. OutputCache attribute
  74. CacheProfiles
  75. RequireHttps attribute
  76. ValidateInput attribute
  77. Custom action filters
  78. Different types of ActionResult in asp.net mvc
  79. Areas
  80. StringLength attribute
  81. Range attribute
  82. Creating custom validation attribute
  83. RegularExpression attribute
  84. Compare attribute
  85. Enable client side validation in asp.net mvc
  86. ValidationSummary
  87. What is Unobtrusive JavaScript
  88. Unobtrusive validation in asp.net mvc
  89. Remote validation in asp.net mvc
  90. Remote validation in mvc when javascript is disabled
  91. Create a custom remote attribute and override IsValid() method
  92. Ajax with asp.net mvc
  93. What is Ajax and why should we use it
  94. Providing visual feedback using LoadingElementId AjaxOption
  95. OnBegin, OnComplete, OnSuccess and OnFailure properties of AjaxOptions class
  96. LoadingElementDuration property of AjaxOptions class
  97. Implement autocomplete textbox functionality in mvc
  98. What is JavaScript minification
  99. What is CDN - Content Delivery Network
  100. What if CDN is down
Reference: http://csharp-video-tutorials.blogspot.co.uk/p/aspnet-mvc-tutorial-for-beginners.html

ASP.NET MVC: Partial Views

If you are an asp.net web-forms developer, then you will realize that partial views in mvc are similar to user controls in asp.net webforms. 

Partial views are used to encapsulate re-usable view logic and are a great means to simplify the complexity of views. These partial views can then be used on multiple views, where we need similar view logic.



f you are using web forms view engine, then the partial views have the extension of .ascx. If the view engine is razor and programming language is c#, then partial views have the extension of .cshtml. On the other hand if the programming language is visual basic, then the extension is .vbhtml.
Partial views in mvc

Let us understand partial views with an example. We want to display, employee photo and his details as shown in the image below.
partial view example

Index Action() method in HomeController retrurns the list of employees.
public ActionResult Index()
{
    SampleDBContext db = new SampleDBContext();
    return View(db.Employees.ToList());
}

We will have the following code in Index.cshtml. This view is a bit messy and complex to understand.
@model IEnumerable<MVCDemo.Models.Employee>
@foreach (var item in Model)
{
    <table style="font-family:Arial; border:1px solid black; width: 300px">
        <tr>
            <td>
                <img src="@Url.Content(item.Photo)" alt="@item.AlternateText" />
            </td>
            <td>
                <table>
                    <tr>
                        <td><b>Age:</b></td>
                        <td>@item.Age</td>
                    </tr>
                    <tr>
                        <td><b>Gender:</b></td>
                        <td>@item.Gender</td>
                    </tr>
                    <tr>
                        <td><b>Salary:</b></td>
                        <td>@item.Salary</td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
}

To simplify this view, let's encapsulate the HTML and code that produces the employee table in a partial view.

Right click on the "Shared" folder and add a view. Set
View name = _Employee
View engine = Razor
Create a strongly typed view = Checked
Model class = Employee (MVCDemo.Models)
Scaffold template = Empty
Create as a partial view = Checked

This should add "_Employee.cshtml" partial view to the "Shared" folder.

Please note that, partial views can be added to "Shared" folder or to a specific views folder. Partial views that are in the "Shared" folder are available for all the views in the entire project, where as partial views in a specific folder are available only for the views with-in that folder.

Copy and paste the following code in "_Employee.cshtml" partial view
@model MVCDemo.Models.Employee
<table style="font-family:Arial; border:1px solid black; width: 300px">
        <tr>
            <td>
                <img src="@Url.Content(Model.Photo)" alt="@Model.AlternateText" />
            </td>
            <td>
                <table>
                    <tr>
                        <td><b>Age:</b></td>
                        <td>@Model.Age</td>
                    </tr>
                    <tr>
                        <td><b>Gender:</b></td>
                        <td>@Model.Gender</td>
                    </tr>
                    <tr>
                        <td><b>Salary:</b></td>
                        <td>@Model.Salary</td>
                    </tr>
                </table>
            </td>
        </tr>
</table>

Now, make the following changes to Index.cshtml view. Notice that the view is much simplified now. To render the partial view, we are using Partial() html helper method. There are several overloaded versions of this method. We are using a version that expects2 parameters, i.e the name of the partial view and the model object.
@model IEnumerable<MVCDemo.Models.Employee>
@foreach (var item in Model)
{
    @Html.Partial("_Employee", item)
}

ASP.NET MVC: Developing Extension in MVC (HTML Helper For Image (@Html.Image): )

Today I worked on a project where I am required to display an image on the web page. As you know there is not a HTML Helper for images yet. Look at the following screen, we can't see an image here:

Developing-Extension-in-MVC.png
Before proceeeding in this article, let me share the sample data source here (I can't share the original data so I created a set of dummy data with a controller here):

Data Source & Controller

Extension-in-MVC.gif

View
Html-Helper-for-Image2.png

As in the above image, the first one (@Html.DisplayFor…) is generated by scaffolding for me (marked as a comment in the above view) and the second one is an alternative that will work.

So, we don't have a HTML helper to deal with images using Razor syntax! Wait wait. We can develop an extension method for this that will allow us to work with images. Let's get started.

Step 1: Add a class file using the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication8.Models
{
    public static class ImageHelper
    {
        public static MvcHtmlString Image(this HtmlHelper helper, string src, string altText, string height)
        {
            var builder = new TagBuilder("img");
            builder.MergeAttribute("src", src);
            builder.MergeAttribute("alt", altText);
            builder.MergeAttribute("height", height);
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }
    }

}
The above "Image" function has the "MvcHtmlString" type and will accept a four-parameter helper (helper type "image"), src (image path), altText (alternative text) and height (height of image) and will return a "MvcHtmlString" type.

Step 2: In the view, comment-out the last line (HTML style approach) and use the new extended method for the image, as in:

Html-Helper-for-Image3.gif

Note: Please note to use "@using MvcApplication8.Models" namespace on each view page to enable this new HtmlHelper.

Step 3: If you put a breakpoint on the extension method then you will notice that the method returns the exact markup that we need.

Extension-method-in-MVC.gif

Hope this helps.

Reference: http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/html-helper-for-image-html-image-developing-extension-in/

ASP.NET MVC: Html Helper Method

Html Helper:
  • To add content to VIEW of Asp.net MVC application, Html Helper is being used.
  • This is nothing but a method which returns string.
  • Html Helper could we used to generate standard HTML elements like Text Box, Label etc.
  • All Html helper are called on the Html property of view. For example to render a Text Box we call Html.TextBox() method.
  • Using Html helper method is optional. Its purpose is to reduce scripting code.
The ASP.NET MVC framework includes the following set of standard HTML Helpers (this is not a complete list):
  • Html.ActionLink()
  •  Html.BeginForm()
  • Html.CheckBox()
  • Html.DropDownList()
  • Html.EndForm()
  • Html.Hidden()
  • Html.ListBox()
  • Html.Password()
  • Html.RadioButton()
  • Html.TextArea()
  • Html.TextBox()
Creating Html Helper method

Custom Html Helper method could we created in two ways
  1. Using static method.
  2. By extension method.
Using static method:
The easiest way to create custom Html helper method is create static method and return a string. Here we are going to create a Html helper method, which will render a label element of Html.

Step 1:

Add a new folder called Helpers in Asp.Net MVC application. 

Step 2:

Add a class in newly created Helpers folder. Right click at folder and then add class namedLableHelper.cs
ViewHelper.gif

Step 3:
Now add static method in this class called Label. This method will return string and will take two string parameters named target and text. 
Code will be like below

using System;using System.Collections.Generic;using System.Linq;using System.Web;
namespace MvcApplication2.Helpers
{
    public class LabelHelper    {
        public static string Label(string target, string text)
        {
            return String.Format("<label for= '{0}'>{1}</label>",target,text);
        }
    }
}


Step 4:

Now, we are going to use Label Html helper in view or aspx page. 

View\Home\Index.aspx

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"Inherits="System.Web.Mvc.ViewPage" %><%@ Import Namespace="MvcApplication2.Helpers" %><asp:Content ID="indexHead" ContentPlaceHolderID="head" runat="server">    <title>Home Page</title></asp:Content>
 <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">    <h2><%= Html.Encode(ViewData["Message"]) %></h2>    <p>        To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
    </p>    <div>    <%using(Html.BeginForm())
      { %> 
        
        <%=LabelHelper.Label("firstName","Firstname"%>    
        
      <% } %>    </div>
</asp:Content>

In above code couples of things are worth noticing.
  1. We have included Namespace for Html Handler method of Label.
  2. Html.BeginForm is inside using , such that after rendering form will get closed.
  3. LabelHelper.Label is preceded by <%=.
As Extension method:
       public static class LabelExtensions
        {            public static string Label(this HtmlHelper helper, string target, string text)
            {                return String.Format("<label for='{0}'>{1}</label>", target, text);
            }
        }
In above code fact noticing are
  1. First parameter to Html Helper method is this . In case of extension method always first parameter is class on which we are extending the method.
  2. Extended method enables us to add new method in existing class.
  3. Here class is static class. We must define Extension method with static class.
  4. Extension method will be read be Intellisense like other method of the class.

Reference:http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/html-helper-method-in-Asp-Net-mvc-application/

ASP.NET MVC : DropDownList Helper Data Binding in MVC

In this article you will learn how to bind data to a DropDownList helper in MVC. We will try binding data to a DropDownList from a List<SelectListItem>, a List<Model> and also from a database.

I've created three DDL helpers on the view page and to bind each DDL we will use a different approach.


Let's bind each DDL using various approaches.

1st Approach

In this approach, I am going to bind a Country DDL with List<SelectListItem> data; here is the code I'm using in the action method.


Notice two things in above code

First: I have created a List<SelectListItem> that is IEnumerable<SelectListItem> and adding 3 items to the country object. The IEnumerable<SelectListItem> created above is added to the ViewBag with the name Country. This is how we pass the IEnumerable<SelectListItem> implicitly to the DDL helper shown below.

@Html.DropDownList("Country"String.Empty)

In the above code, the helper accepts two parameters. The first parameter named DDL ("Country") is a compulsory parameter and it should be similar to the ViewBag (ViewBag.Country) name and the second, optionLabel, is not compulsory. The optionLabel is generally used the for first option in DDL. For example, if I use:

@Html.DropDownList("Country""Select Country")

Then, it will render the following output.


Second: We can pass the IEnumerable<SelectListItem> explicitly to the DropDownList helper or we can add the IEnumerable<SelectListItem> to the ViewBag using the same name for the SelectListItem as the model property, look at the code how four different overloads are arranged.



2nd Approach

In this approach, I am going to bind Language DDL with List<Gender> data. Here the Gender is a predefined model; here is the code I'm using in the action method.


In the above code, rather than add data in country.Add(new SelectListItem { Text = "", Value = "", Selected = "" }), I'm adding to Gender properties that are Id and Name.

3rd Approach

In this approach, I am going to bind Gender DDL with database data.


Again, the database has two fields, Id and Name. The Name field is for a data value field and data text field. "Male" will be the pre-selected value in the DDL.

Complete Action Method Code

Now let me put all the above approaches in the same action method.


Complete View Page Code

I created a quick form and placed all three DDL helpers inside, when the user clicks the submit button the form data will be passed to the POST version of the DDLBinding action method that will be in the Home controller. By default, the Html.BeginForm overload takes no parameters. The no parameter version defaults to posting the form data to the POST version of the same action method and controller.


Now, when the user clicks on the submit button the HTTP POST will execute and the selected items will be passed to the DDLBinding action method that has a POST version with a query string.



Here is the POST version of the DDLBinding action method:


Hope this helps.

Reference:http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/dropdownlist-helper-data-binding-in-mvc/