Archive

Archive for the ‘ASP.NET MVC’ Category

Strongly-typed Custom HtmlHelper in ASP.NET MVC 4

January 6, 2014 Leave a comment

In this post you are going to see how  we can create Strongly-typed Custom  HtmlHelpers in ASP.NET MVC , you can see simple Custom  HtmlHelpers in ASP.NET MVC here .

So before creating Custom  Strongly-typed HtmlHelpers  , let’s see why we need Strongly-typed HtmlHelpers  if we have HtmlHelpers  in mvc already . So lets see below that use an untyped Html helper.

    <%= Html.TextBox(“Name”) %>

It is working as expected but sometime in future  you changed your class Name property from Name to EmplyeeName and same time you did not update View for this property and now your site is in live as you would be not getting any error about this mismatch between view and model at compile time and user on site experiencing that name is not working properly as this is expected as  EmplyeeName while binding view stuff to model property. So I need a mechanism that gets checked at compile time rather than run time that’s where  Strongly typed Html helper come into the picture.  Now see how Strongly typed HTML helper work and its syntax

 <%= Html.TextBoxFor(model => model.Name) %> //Strongly typed HTML helper

If you using Strongly typed HTML helper and changes Name to EmplyeeName then view compilation will be failed. Now , I think you got typed and untyped HTML Helper and its advantage too, so lets proceed to create Strongly-typed Custom  HtmlHelpers.

To create Strongly-typed Custom  HtmlHelpers , you use two classes

ExpressionHelper — Gets the model name from a lambda expression . This is used as ID and name of the field.
ModelMetadata    —  Gets other information about the lambda expression, including its value

so lets see code for it that will use both ExpressionHelper and ModelMetadata    classes

[sourcecode language="csharp"]
namespace MVC4CustomHelper.Helper
{
    public static class CustomHelper
    {
       public static MvcHtmlString CustomTextBox(this HtmlHelper htmlHelper,string name, string value)
        {
            var builder = new TagBuilder("input");
            builder.MergeAttribute("type", "text");
            builder.MergeAttribute("name", name);
            builder.MergeAttribute("value", value);
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }
       public static MvcHtmlString CustomTextBoxFor<TModel, TProperty>
                  (this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
	    // name and ID for Html output
            var name =     ExpressionHelper.GetExpressionText(expression);

            //value for html control
            var metadata = ModelMetadata.FromLambdaExpression(expression,htmlHelper.ViewData);

            return CustomTextBox(htmlHelper, name, metadata.Model as string);
        }

    }
}
[/sourcecode]

Now take references in View or can take references in web config too

[sourcecode language="csharp"]
<%@ Import Namespace="MVC4CustomHelper.Helper" %>
[/sourcecode]

Using created Custom Html Helper method in view

[sourcecode language="csharp"]
<%= Html.CustomTextBoxFor(model => model.Name )%>
[/sourcecode]

you you like this post then do not forget to like and comments 🙂

Categories: ASP.NET MVC Tags:

Custom HTML Helper in MVC 4

January 6, 2014 Leave a comment

If you have worked on MVC before then you must know that there are numbers of built in Html helper method are in MVC  like Html.ActionLink(),Html.RadioButton(),Html.TextArea(),Html.TextBox() etc .So When  a helper method is called in a View using the razor syntax @Html or <%= Html.LabelFor() , Then we actually using  the Html property of the View, which is an instance of the HtmlHelper class.

So to create a custom HTML Helper
— create extension methods for HtmlHelper class.
— System.Web.Mvc.Html contain the extension methods for Html Helper method.
So let’s Create an Custom Html Helper method

Step 1) create extension methods for HtmlHelper class.

namespace MVC4CustomHelper.Helper
{
    public static class CustomHelper
    {
        public static MvcHtmlString CustomTextBox(this HtmlHelper htmlHelper,string name,string value)
        {
            var builder = new TagBuilder("input");
            builder.MergeAttribute("type", "text");
            builder.MergeAttribute("name", name);
            builder.MergeAttribute("value", value);
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
        }

    }
}

Step 2) Taking reference in using View and using it

<%@ Import Namespace="MVC4CustomHelper.Helper" %>

Using created Custom Html Helper method

<%= Html.CustomTextBox("Name",Model.Name )%>

you will notice that it give Intellisense for Custom Html Helper method.
If you like this post the do not forget to like or comment on this 🙂

Categories: ASP.NET MVC Tags:

Custom Action filter in MVC 3

January 5, 2014 Leave a comment

As we know that there are numbers of attribute based filter are provided by MVC framework , but in case that all does not meet our requirement we can create our own custom filter and resister it in our application.so before proceeding with this blog post i would recommend you to visit my blog post Filter in MVC to have basic understanding of what actually filter is and its scope in MVC .

So to create Custom Action filter

–Create a class that would either inherit from ActionFilterAttribute or implement IActionFilter, IResultFilter
–Then use this class as attribute on action method or Controller class.
–Or you can register it globally using Global.asax that basiccaly called Global Action filter that is new feature of MVC 3

let’s first create a class that would either inherit from ActionFilterAttribute

public class MVC3CustomActionAttribute : ActionFilterAttribute//(IActionFilter, IResultFilter)
    {
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {

        }
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            ViewResult view = filterContext.Result as ViewResult;
            if (view != null)
            {
                view.ViewBag.Message = "Changed in OnResultExecuting" + view.ViewData["Message"].ToString();
            }
        }
    }

Then use this class as attribute on action method

[MVC3CustomAction]
public ActionResult Index()
{
   ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
   return View();
}

Or register it globally using Global.asax

public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {

            RegisterGlobalFilters(GlobalFilters.Filters);

        }
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {

            filters.Add(new MVC3CustomActionAttribute());

        }
    }
}

Do not forget to like or comment 🙂

Categories: ASP.NET MVC Tags:

Filter In MVC 3

January 5, 2014 Leave a comment

What is Filter

–As per MSDN “Filters are classes that provide both a declarative and programmatic means to add pre-action and post-action behavior to controller action methods.

–It let perform logic either before an action method is called or after an action method runs.” like before executing an action method of controller you want to process some business logic or some kind validation or checking upon which you determine to excute action method or not or your custome requirements

Kinds of filter in MVC 3

1) Authorization filters
2) Action filters
3) Result filters
4) Exception filters

Note : Filters run in sequence as stated above from 1 to 4

Now lets explore all of them in bit details

1) Authorization filters

–It implement IAuthorizationFilter
–It performe authentication or validate properties of the request.
–The AuthorizeAttribute class and the RequireHttpsAttribute class is example of it ,
–Authorization filters run before any other filter and used as below

[Authorize]
[RequireHttps]
public ActionResult Index()
{
}

2) Action filters

–It implement IActionFilter
–The IActionFilter interface declares two methods: OnActionExecuting and OnActionExecuted.
–OnActionExecuting runs before the action method.
–OnActionExecuted runs after the action method
–OnActionExecuted can do additional processing, like providing extra data to the action method, inspecting the return value, or canceling execution of the action method on which it is applied.

3) Result filters

–implement IResultFilter
–IResultFilter declares two methods: OnResultExecuting and OnResultExecuted
–The OutputCacheAttribute class is one example of a result filter

[OutputCache]
public ActionResult Index()
{
}

4) Exception filters

–It implement IExceptionFilter
–It execute if there is an unhandled exception thrown during the execution of the ASP.NET MVC pipeline
–The HandleErrorAttribute class is one example of an exception filter.

[HandleError]
public class HomeController : Controller
{
}

There are four way you can Create filter

–Override one or more of the controller’s On<Filter> methods.
–Create an attribute class that derives from ActionFilterAttribute and apply the attribute to a controller or an action method.
–Register a filter with the filter provider (the FilterProviders class).
–Register a global filter using the GlobalFilterCollection class.

Categories: ASP.NET MVC Tags:

Custom validation in ASP.NET MVC 3

January 1, 2014 Leave a comment

As you may know that you can implement validation using validation attributes that come in (System.ComponentModel.DataAnnotations namespace) in MVC , although there are numbers of  validation attributes are provided by the framework like  [Required], [Range],  [StringLength], Compare and [RegularExpression]  but it might not fulfill your business requirements, in this case you can write your own validation attribute and use the way you use framework validation attribute so to use custom validation , first write a class that inherit from abstract ValidationAttribute class and  override virtual  IsValid method with your business requirement of this class and then use it as validation attributes.  let’s implement a basic CreditCard custom validation rule .

Step 1  : Writing a class that inherit from ValidationAttribute class

public class CreditCardAttribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            var number = Convert.ToString(value);
            if (String.IsNullOrEmpty(number))
                return true;

            return IsValidCardNumber(number);
        }

        private bool IsValidCardNumber(string cardNumber)
        {
            if (Regex.IsMatch(cardNumber, "^(4)"))
                return cardNumber.Length == 16;
            return false;
        }

        public override string FormatErrorMessage(string name)
        {
            return "The " + name + " field contains an invalid credit card number.";
        }
    }

Step 1 : Putting this as validation attribute

public class User
    {
        [CreditCard]
        public string CreditCard { get; set; }
    }

I hope I could put as simple as possible . Thanks for being around on this post :).

Categories: ASP.NET MVC Tags:

Html.ActionLink VS Html Anchar Tag ()

September 18, 2013 Leave a comment

Here ,in this post i am going to describe about MVC Html.ActionLink and normal anchor tag and which one is best for use.

Html.ActionLink

Html.ActionLink use current routing configuration in Gloabl.asax.cs to prepare hyperlink at runtime. so when you modify your routing setting in said global file then Html.ActionLink directly  reference modified routing settings that you will  see below in this blog.

Anchar Tag ()

if  you use anchar tag then there is chance that your links will be broken in case routing configuration in Gloabl.asax.cs is changed. So always use Html.ActionLink over Anchar Tag that will save you time as you do not have to change all anchar tag manually  when routing configuration in Gloabl.asax.cs is changed .

Now, let’s experince this visually, Intially it is “Home/TestIndex” set as routing configuration in Gloabl.asax.cs as below and hyperlink is implemented in two way 1) Using Action Link 2) using Anchor Tag in view

Gloabl.asa


public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
"CustomeTest", // Route name
"Home/TestIndex",
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
<pre>

HTML that using hyperlink in two way 1) Using Action Link 2) using Anchor Tag

<div>
<a href="../../Home/TestIndex">Back to Home (Simple Anchor Tag) </a>
<br />
<br />
@Html.ActionLink("Back to Home (Mvc Action Link)", "Index")
</div>

Now see it visually

PIC1

Here , when Back to Home (Simple Anchor Tag) link is clicked  it redirecting to home page properly .Now let’s change routing setting from “Home/TestIndex” to “Home/SuperIndex” as below then try to access same link to go to Home Page.

Pic2

so When Route settings is changed in Global.asax file then Html.ActionLink is modified accordingly but simple Anchor tag remain same so when simple Anchor tag link is clicked then you will get page not found  as below. But when link made by Html.ActionLink is clicked then it is opening concerned page properly as its Url / Hperlink is modified according to the route settings in global file

Pic3Hope you got the concept behind Html.ActionLink over Simple Anchar tag . And yes , if this post interest you then do not forget to like and comment . You can download source code from here Download Me

Thanks for your time 🙂

The Controls collection cannot be modified because the control contains code blocks(i.e. )


Introduction:
In this post i am going to reason two things:
(1)why error “The Controls collection cannot be modified because the control    contains code blocks (i.e. <% … %>) ” come.
(2)How to solve same

Cause of error
When you add any AJAX extenders to your Web pages of your web application or try to add something in page header of web pages , it  register  scripts in the head dynamically and if any code blocks(like <% … %>) are present in the MasterPage, an error might occur.

My script in master page

<head id="head2" runat="server">
<title>Lightbox Page</title>
 <script type="text/javascript" src="<%= ResolveUrl("~/js/jquery-1.7.2.js") %>"></script>
 <script type="text/javascript" src="<%= ResolveUrl("~/js/script.js") %>"></script>
</head>

Error screen shot

Many method of solving same are:

First Method

Replace the code block with <%# instead of <%=


<script type="text/javascript" src="<%= ResolveUrl("~/js/jquery-1.7.2.js") %>"></script>
to
<script type="text/javascript" src="<%# ResolveUrl("~/js/jquery-1.7.2.js") %>"></script>

and then add this line in page load of web pages in master pages or child page( in my case it was master page.)
Page.Header.DataBind();
like

protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
}

Second Method
Remove JavaScript from the header section of web page and add it to body of the web page .
Third method
Place all your script inside <asp:placeholder runat=”server”> in header of web page
like

<head runat="server">
 <asp:ContentPlaceHolder ID="ScriptIncludePlaceHolder" runat="server">
    <script type="text/javascript" src="<%= ResolveUrl("~/js/jquery-1.7.2.js") %>"></script>
 </asp:ContentPlaceHolder>
</head>

Doing this makes code block a child of the Placeholder control, instead of being a direct child of the Page.Header control.

I hope this Will help you in solving you problem. If it help you just drop a feedback.And Any suggestion is welcomed.

Categories: ASP.NET, ASP.NET MVC, Error Tags:
%d bloggers like this: