Thursday, November 6, 2014

Using the DropDownList Helper with ASP.NET MVC

No comments:

This post will teach you the basics of working with the DropDownList helper helper in an ASP.NET MVC Web application.
The DropDownList helper used to create an HTML select list requires a IEnumerable , either explicitly or implicitly. That is, you can pass the IEnumerable explicitly to the DropDownList helper or you can add the IEnumerable to the ViewBag using the same name for the SelectListItem as the model property.
Let's suppose you want to show list of Animals as dropdownlist

public static List<String> GetPets()
        {
            List<string> petList = new List<string>();
            petList.Add("Dog");
            petList.Add("Cat");
            petList.Add("Hamster");
            petList.Add("Parrot");
            petList.Add("Gold fish");
            petList.Add("Mountain lion");
            petList.Add("Elephant");

            return petList;
        }

Open your controller method and add items to ViewBag item by passing the item to SelectList.

public ActionResult Index()
        {

            ViewData["Pets"] = new SelectList(GetPets());
            return View();
        }

In your view add following razor helper method.Run the application you will see that dropdownlist is generaeted

@Html.DropDownList("pets")

The above was very simple form.Let's create a complex form with some other information.In this example I am going to create a simple user registration form.Create two class named Country and Registration in model folder and add following code


public class Registration
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string County { get; set; }

    }
    public class Country
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

After that create a RegistrationViewModel class in Model folder and paste the following code

public class RegistrationViewModel
    {
        private readonly List<Country> _countries;
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string County { get; set; }

        public int SelectedCountryID { get; set; }
        public RegistrationViewModel()
        {
            List<Country> countries = new List<Country>(){
                new Country{Id=1,Name="India"},
                new Country{Id=2,Name="USA"},
                new Country{Id=3,Name="UK"},
                new Country{Id=4,Name="Australia"},
                new Country{Id=5,Name="Nepal"},
            };
            _countries = countries;
        }
        public IEnumerable<SelectListItem> Contry
        {
            get { return new SelectList(_countries, "Id", "Name"); }
        }
    }
The tricky part here is that I have added a readonly property Country that returns list of countries which I will pass to DropDownListFor helper function.Create two action methods in your controller as below.Right click on Create action method and generate strongly type view.Open the genrated view and modify the Country section as below

      <div class="editor-field">
            @Html.DropDownListFor(model => model.SelectedCountryID, Model.Contry)
            @Html.ValidationMessageFor(model => model.County)

        </div>


public ActionResult Create()
        {
            RegistrationViewModel model = new RegistrationViewModel();
            return View(model);
        }
        [HttpPost]
        public ActionResult Create(RegistrationViewModel _model)
        {
            RegistrationViewModel model = _model;
            return View(model);
        }


@model eManagerDemo.Models.RegistrationViewModel

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>RegistrationViewModel</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.County)
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.SelectedCountryID, Model.Contry)
            @Html.ValidationMessageFor(model => model.County)

        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

If you run the application by pressing F5 you will see following output as shown in below image.


Read More

How to create html helper in razor (.NET MVC)

No comments:

Razor is an ASP.NET programming syntax used to create dynamic web pages with the C# or Visual Basic .NET programming languages.The Razor syntax is a template markup syntax, based on the C# programming language, that enables the programmer to use an HTML construction workflow[clarification needed]. Instead of using the ASP.NET .ASPX markup syntax with <%= %> symbols to indicate code blocks, Razor syntax starts code blocks with a @ character and does not require explicit closing of the code-block.

HTML Helper
Html helper are much like asp.net control that return html string.But HTML helpers are more lightweight. Unlike Web Form controls, an HTML helper does not have an event model and a view state.
In this post I will show you how to create Html helper in MVC.NET.There are two ways to create html helper in MVC.
Inline Helpers
These are create in the same view by using the Razor @helper tag. These helpers can be reused only on the same view.For example in following code snippet I have created a ToUpper html helper that wrap the text inside b tag and converts  the text to upper case 

@helper ToUpper(string text) { 
        
        @text.ToUpper()
    
    }
@{
    ViewBag.Title = "Demo";
    Layout = null;
}


@ToUpper(@ViewBag.Message)

Custom Helper
If you want to use your Html helper in application level then you can create custom helper.
You can create custom helper function by creating extensions method.In following code snippet I have created a SubmitButton html helper that generate submit button.



public static class HtmlHelpers
    {
        public static MvcHtmlString SubmitButton(this HtmlHelper helper, string text)
        {
            string str = "<input type=\"submit\" value=\"" + text + "\" />";
            return new MvcHtmlString(str);
        }
    }

How to use custom Helper

@Html.ToUpper("Submit")
Read More

Saturday, November 1, 2014

How to check stream has Image or not

No comments:
Let's suppose you have a page on which user upload there image and you want to validate that user is uploading image file only not other file format.The one easy solution is use regex and validate the extension of the file but if user rename the extension of the file and upload some executable code.Following is the simple c# code snippet that check the file type by the header value.

private bool IsImage()
    {
        bool isImage = false;
        FileStream stream = new FileStream(Server.MapPath(@"Images\a.txt"), FileMode.Open, FileAccess.Read);
        StreamReader reader = new StreamReader(stream);
        // Read the first 25 characters, we will be checking for a GIF or JPG signature.
        char[] strBuffer = new char[25];
        reader.ReadBlock(strBuffer, 0, 25);
        string stringBuffer = new string(strBuffer);
        // Is this an image?
        if (stringBuffer.IndexOf("GIF8") &gt; -1 || stringBuffer.IndexOf("JFIF") &gt; -1)
        {
            isImage = true;
            Response.Write("It's an image");

        }
        else
        {
            Response.Write("It's HTML or other junk.");
        }
        return isImage;
    }
Read More

How To Change your ASP.Net controls at runtime

No comments:
Lets say you are working in a fairly large asp.net application. Now because of situation (or clients request) you want to change all the textbox or button control to some server control or user control. This can be very very tedious JOB if you are using Asp.net 1.X. But if you are using Asp.net 2.0 , there is a very easy way to get this done using tagMapping
it’s a way to turn all instances of a type into another type at compile time. In human language it means that it can turn all e.g. System.Web.UI.WebControls.Textbox (in our example ) instances in the entire website into another control.That is so cool that I had to do a little example. I’ve created a very simple control that inherits from a TextBox and overrides the Text property so that it HTML encodes the text. I placed it in the App_Code folder and called it SafeTextBox.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
///
/// Summary description for SafeTextBox
///
public class SafeTextBox : System.Web.UI.WebControls.TextBox
{
    public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {
            base.Text = System.Web.HttpUtility.HtmlEncode(value);
        }
    }
}

Then I needed to hook the tag mapping up in the web.config to convert all the text boxes into SafeTextBox instances. It simply converts all TextBox instances on the entire site. Here is what’s needed in the web.config:

<pages> <tagMapping> <add tagType="System.Web.UI.WebControls.TextBox" mappedTagType="SafeTextBox"/> </tagMapping> </pages>
After we add the following line of code in the web.config file all the TextBox control will be mapped to the TextBox.
Read More

How to change some text before it is sent to the client.

No comments:

In this post,I will show you how to modify the response before it is sent to the client.The trick here is to override the Render method of the Page class and modify the response.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="InterceptHtml.aspx.cs"
Inherits="InterceptHtml" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           Hello World!
           <br />
           Hi
       </div>
   </form>
</body>
</html>

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;

public partial class InterceptHtml : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {

       Response.Filter = new ReplaceHTML(Response.Filter);


   }
   /// <summary>
   /// Second Method!!!!!!! overide the Render Method.
   /// </summary>
   /// <param name="writer"></param>
   protected override void Render(HtmlTextWriter writer)
   {


       StringWriter output = new StringWriter();
       base.Render(new HtmlTextWriter(output));
       writer.Write(output.ToString().Replace("Hi", "This is the replaced text!
Welcome to <a href=\"http://www.aspdotnetcodebook.blogspot.com\
">www.aspdotnetcodebook.blogspot.com</a>"));
   }
}
II nd Method
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

/// <summary>
/// To intercept and get a reference to the HTML, we now need to create a
/// class to inherit System.IO.Stream. So, create a new class in
/// </summary>
public class ReplaceHTML : System.IO.Stream
{

    private System.IO.Stream Base;

    public ReplaceHTML(System.IO.Stream ResponseStream)
    {
        if (ResponseStream == null)
            throw new ArgumentNullException("ResponseStream");
        this.Base = ResponseStream;
    }






    public override int Read(byte[] buffer, int offset, int count)
    {
        return this.Base.Read(buffer, offset, count);
    }


    public override void SetLength(long value)
    {

    }

    public override void Write(byte[] buffer, int offset, int count)
    {
        // Get HTML code 
        string HTML = System.Text.Encoding.UTF8.GetString(buffer, offset, count);

        // Replace the text with something else 
        HTML = HTML.Replace("Hello World!", "I've replaced the Hello World example!");

        // Send output 
        buffer = System.Text.Encoding.UTF8.GetBytes(HTML);
        this.Base.Write(buffer, 0, buffer.Length);
    }

    public override bool CanRead
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override bool CanSeek
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override bool CanWrite
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override void Flush()
    {
        HttpContext.Current.Response.Flush();

    }

    public override long Length
    {
        get { throw new Exception("The method or operation is not implemented."); }
    }

    public override long Position
    {
        get
        {
            throw new Exception("The method or operation is not implemented.");
        }
        set
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }

    public override long Seek(long offset, System.IO.SeekOrigin origin)
    {
        throw new Exception("The method or operation is not implemented.");
    }
}
Read More