ASP.NET 4.5 and ASP.NET Core 1 Hosting BLOG

Tutorial and Articles about ASP.NET 4.0 and the latest ASP.NET 4.5 Hosting

ASP.NET 5 Hosting - ASPHostPortal.com :: Debugging jQuery in ASP.NET

clock February 10, 2015 07:17 by author Mark

When an ASP.NET developer uses jQuery or JavaScript (clientside programming) in his code, the question always arises of how to debug this code. We can debug in code behind with breakpoints. But what for clientside scripting. Some people say use "alert()", but I don't think this is a sufficient way to do it.
So the good news is that we have the "debugger" keyword to debug your line of code.
Use debugger before your code, where you want to start debugging.
See the following code:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title></title>
        <script src="Scripts/jquery-1.7.1.min.js"></script>
        <script>
            $(document).ready(function () {
                $(':radio').click(function () {
                    debugger;
    //Get the value of Radio button
                    var _GetVal = $(this).attr('value');
                });
             });
        </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
           First
            <input type="radio" name="rd1" value="10" />
            <input type="radio" name="rd1" value="11" />
            Second
            <input type="radio" name="rd1" value="12" />
            <input type="radio" name="rd1" value="13" />
        </div>
        </form>
    </body>
    </html>

This is a simple ASP.NET in page code. When the user clicks a radio button, debugging will automatically start, due to the debugger command. In the above program, when the user clicks on the radio button we stored its value in the _Getval variable.

$(document).ready(function () {
                $(':radio').click(function () {
                    debugger;
    //Get the value of Radio button
                    var _GetVal = $(this).attr('value');
                });
             });

You can see that when I declare a _GetVal variable, before I use "debugger" because from here I want to start debugging. See the following images.
Figure 1: When user clicks in the radio

Figure 2: When the user presses F10 (the same way as what we did in code behind using a breakpoint).

In the image above you can see that the _GetVal value is 10 now. So with the use of the debugger you can start your debugging in ASP.NET.
And please remember, when you finish debugging or publish your page, please remove debugger from your code.
If you have any query, Please send your valuable Comments. Happy Programming

TOP No#1 Recommended ASP.NET Hosting

ASPHostPortal.com

ASPHostPortal.com  is the leading provider of Windows hosting and affordable ASP.NET Hosting. ASPHostPortal proudly working to help grow the backbone of the Internet, the millions of individuals, families, micro-businesses, small business, and fledgling online businesses. ASPHostPortal has ability to support the latest Microsoft and ASP.NET technology, such as: WebMatrix, WebDeploy, Visual Studio 2015, .NET 5/ASP.NET 4.5.2, ASP.NET MVC 6.0/5.2, Silverlight 6 and Visual Studio Lightswitch, ASPHostPortal guarantees the highest quality product, top security, and unshakeable reliability, carefully chose high-quality servers, networking, and infrastructure equipment to ensure the utmost reliability.



ASP.NET 4.5 HOSTING - ASPHostPortal.com :: A simple SPA with AngularJs, ASP.NET MVC, Web API and EF

clock November 14, 2014 06:41 by author Mark

Introduction

SPA stands for Single Page Application. Here I will demonstrate a simple SPA with ASP.NET MVC, Web API and Entity Framework. I will show a trainer profile and its CRUD operation using AngularJS, ASP.NET MVC, Web api and Entity Framework.

Step 1: Create a ASP.NET MVC application with empty template

  • Open visual studio, Got to File->New->Project
  • Select Template -> Visual C# -> Web -> ASP.NET MVC 4 Web application and click OK
  • Select Empty Template and Razor as view engine

Step 2: Install required packages

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

  • PM> Install-Package jQuery
  • PM> Install-Package angularjs -Version 1.2.26
  • PM> Install-Package Newtonsoft.Json
  • PM> Install-Package MvcScaffolding

Step 3: Create Connection String

Create connection string and name DB name as SPADB
    <connectionStrings>
  <add name="SPAContext" connectionString="Data Source=.\sqlexpress;Initial Catalog=SPADB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</connectionStrings>

Step 4: Create model

Create Trainer model
    public class Trainer
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Venue { get; set; }
}

Step 5: Create Repository

Create repository for Trainer model.

Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to create repository. I used repository pattern for well-structured and more manageable.

PM> Scaffold Repository Trainer

After running the above command you will see SPAContext.cs and TrainerRepository.cs created in Model folder. For well manageability, I create a directory name Repository and put these two files in the Repository folder. So change the namespace as like SPA.Repository instead of SPA.Model. I also create a UnitOfWork for implement unit of work pattern.
The overall folder structure looks like following. 
SPAContext.cs
    public class SPAContext : DbContext
{
    public SPAContext()
        : base("SPAContext")
    {
    }
    // You can add custom code to this file. Changes will not be overwritten.
    //
    // If you want Entity Framework to drop and regenerate your database
    // automatically whenever you change your model schema, add the following
    // code to the Application_Start method in your Global.asax file.
    // Note: this will destroy and re-create your database with every model change.
    //
    // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<SPA.Models.SPAContext>());
    public DbSet<SPA.Models.Trainer> Trainers { get; set; }
    public DbSet<SPA.Models.Training> Trainings { get; set; }
}

TrainerRepository.cs
    public class TrainerRepository : ITrainerRepository
{
    SPAContext context = new SPAContext();
    public TrainerRepository()
        : this(new SPAContext())
    {
    }
    public TrainerRepository(SPAContext context)
    {
        this.context = context;
    }
    public IQueryable<Trainer> All
    {
        get { return context.Trainers; }
    }
    public IQueryable<Trainer> AllIncluding(params Expression<Func<Trainer, object>>[] includeProperties)
    {
        IQueryable<Trainer> query = context.Trainers;
        foreach (var includeProperty in includeProperties)
        {
            query = query.Include(includeProperty);
        }
        return query;
    }
    public Trainer Find(long id)
    {
        return context.Trainers.Find(id);
    }
    public void InsertOrUpdate(Trainer trainer)
    {
        if (trainer.Id == default(long))
        {
            // New entity
            context.Trainers.Add(trainer);
        }
        else
        {
            // Existing entity
            context.Entry(trainer).State = System.Data.Entity.EntityState.Modified;
        }
    }
    public void Delete(long id)
    {
        var trainer = context.Trainers.Find(id);
        context.Trainers.Remove(trainer);
    }
    public void Save()
    {
        context.SaveChanges();
    }
    public void Dispose()
    {
        context.Dispose();
    }
}
public interface ITrainerRepository : IDisposable
{
    IQueryable<Trainer> All { get; }
    IQueryable<Trainer> AllIncluding(params Expression<Func<Trainer, object>>[] includeProperties);
    Trainer Find(long id);
    void InsertOrUpdate(Trainer trainer);
    void Delete(long id);
    void Save();
}

UnitOfWork.cs
public class UnitOfWork : IDisposable
{
    private SPAContext context;
    public UnitOfWork()
    {
        context = new SPAContext();
    }
    public UnitOfWork(SPAContext _context)
    {
        this.context = _context;
    }
    private TrainingRepository _trainingRepository;
 
    public TrainingRepository TrainingRepository
    {
        get
        {
            if (this._trainingRepository == null)
            {
                this._trainingRepository = new TrainingRepository(context);
            }
            return _trainingRepository;
        }
    }
    private TrainerRepository _trainerRepository;
    public TrainerRepository TrainerRepository
    {
        get
        {
            if (this._trainerRepository == null)
            {
                this._trainerRepository = new TrainerRepository(context);
            }
            return _trainerRepository;
        }
    }
    public void Dispose()
    {
        context.Dispose();
        GC.SuppressFinalize(this);
    }
}

Step 6: Add migration

  • Run the following command to add migration
  • PM> Enable-Migrations
  • PM> Add-Migration initialmigration
  • PM> Update-Database –Verbose

Step 7: Create API Controllers

Create Trainers api Controllers by clicking right button on Controller folder and scaffold as follows.

Step 8: Modify Controllers

Now modify the controllers as follows. Here I used unit of work pattern.
    public class TrainersController : ApiController
{
    private UnitOfWork unitOfWork = new UnitOfWork();
    public IEnumerable<Trainer> Get()
    {
        List<Trainer> lstTrainer = new List<Trainer>();
        lstTrainer = unitOfWork.TrainerRepository.All.ToList();
        return lstTrainer;
    }
    //// GET api/trainers/5
    public Trainer Get(int id)
    {
        Trainer objTrainer = unitOfWork.TrainerRepository.Find(id);
        return objTrainer;
    }
    public HttpResponseMessage Post(Trainer trainer)
    {
        if (ModelState.IsValid)
        {
            unitOfWork.TrainerRepository.InsertOrUpdate(trainer);
            unitOfWork.TrainerRepository.Save();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
    private IEnumerable<string> GetErrorMessages()
    {
        return ModelState.Values.SelectMany(x => x.Errors.Select(e => e.ErrorMessage));
    }
    // PUT api/trainers/5
    public HttpResponseMessage Put(int Id, Trainer trainer)
    {
        if (ModelState.IsValid)
        {
            unitOfWork.TrainerRepository.InsertOrUpdate(trainer);
            unitOfWork.TrainerRepository.Save();
            return new HttpResponseMessage(HttpStatusCode.OK);
        }
        else
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
    }
    // DELETE api/trainers/5
    public HttpResponseMessage Delete(int id)
    {
        Trainer objTrainer = unitOfWork.TrainerRepository.Find(id);
        if (objTrainer == null)
        {
            return new HttpResponseMessage(HttpStatusCode.InternalServerError);
        }
        unitOfWork.TrainerRepository.Delete(id);
        unitOfWork.TrainerRepository.Save();
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

Step 9: Create Layout and Home Controller

Create _Layout.cshtml in Views->Shared folder and create HomeController and create inext view of Home controller by right click on index action and add view. You will see index.cshtml is created in Views->Home
Home Controller
    public class HomeController : Controller
{
    //
    // GET: /Home/
 
    public ActionResult Index()
    {
        return View();
    }
}

_Layout.cshtml
    <html ng-app="registrationModule">
<head>
    <title>Training Registration</title>
</head>
<body>
    @RenderBody()
</body>
</html>
Index.cshtml
    @{
    ViewBag.Title = "Home";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Home</h2>
<div>
    <ul>     
        <li><a href="/Registration/Trainers">Trainer Details</a></li>
        <li><a href="/Registration/Trainers/add">Add New Trainer</a></li>
    </ul>
</div>
<div ng-view></div>

Step 10: Create registrationModule

Create registrationModule.js in Scripts->Application. This is for angularjs routing.
    var registrationModule = angular.module("registrationModule", ['ngRoute', 'ngResource'])
    .config(function ($routeProvider, $locationProvider) {
        $routeProvider.when('/Registration/Trainers', {
            templateUrl: '/templates/trainers/all.html',
            controller: 'listTrainersController'
        });
        $routeProvider.when('/Registration/Trainers/:id', {
            templateUrl: '/templates/trainers/edit.html',
            controller: 'editTrainersController'
        });
        $routeProvider.when('/Registration/Trainers/add', {
            templateUrl: '/templates/trainers/add.html',
            controller: 'addTrainersController'
        });
        $routeProvider.when("/Registration/Trainers/delete/:id", {
            controller: "deleteTrainersController",
            templateUrl: "/templates/trainers/delete.html"
        });
        $locationProvider.html5Mode(true);
    });

Step 11: Create trainerRepository

Create trainerRepository.js in Scripts->Application->Repository. This increase manageability for large application.
    'use strict';
//Repository for trainer information
registrationModule.factory('trainerRepository', function ($resource) {
    return {
        get: function () {
            return $resource('/api/Trainers').query();
        },
        getById: function (id) {
            return $resource('/api/Trainers/:Id', { Id: id }).get();
        },
        save: function (trainer) {
            return $resource('/api/Trainers').save(trainer);
        },
        put: function (trainer) {
            return $resource('/api/Trainers', { Id: trainer.id },
                {
                    update: { method: 'PUT' }
                }).update(trainer);
        },
        remove: function (id) {
            return $resource('/api/Trainers').remove({ Id: id });
        }
    };
});

Step 12: Create trainerController

Create trainerController.js in Scripts->Application->Controllers
    'use strict';
//Controller to get list of trainers informaion
registrationModule.controller("listTrainersController", function ($scope, trainerRepository, $location) {
    $scope.trainers = trainerRepository.get();
});
//Controller to save trainer information
registrationModule.controller("addTrainersController", function ($scope, trainerRepository, $location) {
    $scope.save = function (trainer) {
        trainer.Id = 0;
        $scope.errors = [];
        trainerRepository.save(trainer).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
    };
});

//Controller to modify trainer information
registrationModule.controller("editTrainersController", function ($scope,$routeParams, trainerRepository, $location) {
    $scope.trainer = trainerRepository.getById($routeParams.id);
    $scope.update = function (trainer) {
        $scope.errors = [];
        trainerRepository.put(trainer).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
    };
});
//Controller to delete trainer information
registrationModule.controller("deleteTrainersController", function ($scope, $routeParams, trainerRepository, $location) {
        trainerRepository.remove($routeParams.id).$promise.then(
            function () { $location.url('Registration/Trainers'); },
            function (response) { $scope.errors = response.data; });
});

Step 13: Create templates

Create all.html, add.html, edit.html, delete.html in templateds->trainers folder.
All.html
    <div>
    <div>
        <h2>Trainers Details</h2>
    </div>
</div>
<div>
    <div>
        <table>
            <tr>
                <th>Name </th>
                <th>Email </th>
                <th>Venue </th>
                <th>Action</th>
            </tr>
            <tr ng-repeat="trainer in trainers">
                <td>{{trainer.name}}</td>
                <td>{{trainer.email}}</td>
                <td>{{trainer.venue}}</td>
                <td>
                    <a title="Delete" ng-href="/Registration/Trainers/delete/{{trainer.id}}">Delete</a>
                    |<a title="Edit" ng-href="/Registration/Trainers/{{trainer.id}}">Edit</a>
                </td>
            </tr>
        </table>
    </div>
</div>

Add.html
    <form name="trainerForm" novalidate ng-submit="save(trainer)">
    <table>
        <tbody>
            <tr>
                <td>Trainer Name
                </td>
                <td>
                    <input name="name" type="text" ng-model="trainer.name" required ng-minlength="5" />
                </td>
            </tr>
            <tr>
                <td>Email
                </td>
                <td>
                    <input name="email" type="text" ng-model="trainer.email" />
                </td>
            </tr>
            <tr>
                <td>Venue
                </td>
                <td>
                    <input name="venue" type="text" ng-model="trainer.venue" />
                </td>
            </tr>
            <tr>
                <td class="width30"></td>
                <td>
                    <input type="submit" value="Save" ng-disabled="trainerForm.$invalid" />
                    <a href="/Registration/Trainers" class="btn btn-inverse">Cancel</a>
                </td>
            </tr>
        </tbody>
    </table>
</form>
Edit.html
    <form name="trainerFrom" novalidate abide>
    <table>
        <tbody>
            <tr>
                <td>
                    <input name="id" type="hidden" ng-model="trainer.id"/>
                </td>
            </tr>
            <tr>
                <td>Name
                </td>
                <td>
                    <input name="name" type="text" ng-model="trainer.name" />
                </td>
            </tr>
            <tr>
                <td>Email
                </td>
                <td>
                    <input name="email" type="text" ng-model="trainer.email" />
                </td>
            </tr>
            <tr>
                <td>Venue
                </td>
                <td>
                    <textarea name="venue" ng-model="trainer.venue"></textarea>
                </td>
            </tr>
            <tr>
                <td class="width30"></td>
                <td>
                    <button type="submit" class="btn btn-primary" ng-click="update(trainer)" ng-disabled="trainerFrom.$invalid">Update</button>
                </td>
            </tr>
        </tbody>
    </table>
</form>

Step 14: Add references to the Layout

Modify the _Layout.cshtml to add references
_Layout.cshtml
    <html ng-app="registrationModule">
<head>
    <title>Training Registration</title>
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/angular-resource.min.js"></script>
    <script src="~/Scripts/angular-route.min.js"></script>
    <script src="~/Scripts/jquery-2.1.1.min.js"></script>
    <script src="~/Scripts/Application/registrationModule.js"></script>
    <script src="~/Scripts/Application/Repository/trainerRepository.js"></script>
    <script src="~/Scripts/Application/Controllers/trainersController.js"></script>
</head>
<body>
    @RenderBody()
</body>
</html>

Now run you application and add, delete, modify and get all trainer information. Thanks for your patient! Laughing



ASP.NET 4.5 HOSTING - ASPHostPortal :: Design application layout by bootstrap theme

clock November 12, 2014 06:48 by author Mark

To design layout of your web site is much more cumbersome. But you can easily design your website layout by bootstrap, you can make it responsive also.

Step 1: Create a ASP.NET MVC application with empty template

  • Open visual studio, Got to File->New->Project
  • Select Template -> Visual C# -> Web -> ASP.NET MVC  Web application and click OK
  • Select Empty Template and Razor as view engine

Step 2: Install required packages

  • Run the following command in Package Manager Console (Tools->Library Package Manager->Package Manager Console) to install required package. Make sure your internet connection is enabled.

PM> Install-Package bootstrap

Step 3: Download bootstrap theme

  • Go to http://bootswatch.com/ . Download any theme (bootstrap.css) like below and pest the content in Contents -> bootstrap-main-theme.css file

Step 4: Create a Layout page

  • Create a _Layout.cshtml in Views->Shared folder and add the following references.

_Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <title>Bootstrap theme test</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-main-theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
 </head>
<body>  
    <div>
        @RenderBody()
    </div>
</body>
</html>

Step 5: Create HomeController and index view

  • Create HomeController and create index view. Right click on index action of home controller you will see index.cshtml file created in Views->Home folder. Modify the index.cshtml file like following

Index.cshtml

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
 <h2>Home Page</h2>

Step 6: Add Navigation bar

  • If you go the preview of the theme you will see some sample code or documentation. You can customize later. To add navigation bar to the website I modify the _Layout.cshtml like following.

_Layout.cshtml

<!DOCTYPE html>
 <html>
<head>
    <title>Bootstrap theme test</title>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <link href="~/Content/bootstrap-main-theme.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/bootstrap.js"></script>
 </head>
<body>
    <div class="navbar navbar-inverse">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-inverse-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>
  <div class="navbar-collapse collapse navbar-inverse-collapse">
    <ul class="nav navbar-nav">
      <li class="active"><a href="#">Active</a></li>
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li class="dropdown-header">Dropdown header</li>
          <li><a href="#">Separated link</a></li>
          <li><a href="#">One more separated link</a></li>
        </ul>
      </li>
    </ul>
    <form class="navbar-form navbar-left">
      <input type="text" class="form-control col-lg-8" placeholder="Search">
    </form>
    <ul class="nav navbar-nav navbar-right">
      <li><a href="#">Link</a></li>
      <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
        <ul class="dropdown-menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li class="divider"></li>
          <li><a href="#">Separated link</a></li>
        </ul>
      </li>
    </ul>
  </div>
</div>
    <div>
        @RenderBody()
    </div>
</body>
</html>

Now run the application, you will get a nice layout. Thanks for your patient Smile



ASP.NET 4.5 Hosting - ASPHostPortal.com :: How to use Rangevalidator control in ASP.NET 4.5

clock November 7, 2014 06:26 by author Mark

If you want to understand how RangeValidator  control work in ASP.NET 4.5 Now, we will discuss about How to Use Rangevalidator control in ASP.NET 4.5. Rangevalidator control is used to check if the value is within a specified range of values. For example, Rangevalidator can be used to check if the age between 1 until 100.

In the codesnippet below, TextBox txtAge get age of the person. If User fill with any number that isn’t between 1 – 100 the validation fails. The minimum and maximum value for the age is specified by MinimumValue and MaximumValue properties. Since, Age is an integer, the Type is specified as integer. Write the code below:

&lt;asp:TextBox ID="txtAge" runat="server"&gt;&lt;/asp:TextBox&gt;
&lt;asp:RangeValidator ID="RangeValidator1" runat="server"
    ErrorMessage="Age must be between 1 &amp; 100"
    MinimumValue="1" MaximumValue="100"
    ControlToValidate="txtAge" Type="Integer" &gt;
&lt;/asp:RangeValidator&gt;

Properties for Rangevalidator control:

Type – Specifies the data type of the value to check. Data types supported include Currency, Date, Double, Integer and String.

MinimumValue – Minimum value that allowed

MaximumValue – Max value allowed in that field

The Rangevalidator only checks if the data is within the allowed range. If you wanna check for a required field, use RequiredFieldValidator. In the Age field, I am using both RequiredFieldValidator & RangeValidator. In this example I am using the Display property. If the Display property is not set, or, if it is set to static, then the error message will be rendered, with style visibility:hidden. Then the error message will always occupy the gap on the screen even if the validation passes.

<table>
    <tr>
        <td>
            <b>Age</b>
        </td>
        <td>
            :<asp:TextBox ID="txtAge" runat="server" Width="150px">
                </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorAge" runat="server"
                ErrorMessage="Age must be between 1 & 100"
                MinimumValue="1" MaximumValue="100"
                ControlToValidate="txtAge" Type="Integer"
                ForeColor="Red" Display="Dynamic">
            </asp:RangeValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorAge"
            runat="server" ErrorMessage="Age is required"
            ControlToValidate="txtAge" ForeColor="Red"
            Display="Dynamic" >
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <b>Date Available</b>
        </td>
        <td>
            :<asp:TextBox ID="txtDateAvailable" runat="server" Width="150px">
            </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorDateAvailable" runat="server"
                ErrorMessage="Date must be between 01/01/2012 & 31/12/2012"
                MinimumValue="01/01/2012" MaximumValue="31/12/2012"
                ControlToValidate="txtDateAvailable" Type="Date"
                ForeColor="Red">
            </asp:RangeValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Button ID="btnSave" runat="server" Text="Save" Width="100px"
                onclick="btnSave_Click" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblStatus" runat="server" Font-Bold="true">
            </asp:Label>
        </td>
    </tr>
</table>

This pushes “Age is Required” error message to the correct. To correct this we’ve got set Display=”Dynamic”. This renders the error message with style display:none. If a tag has this style, it’ll not occupy space when not visible.
Code-Behind page code
:
protected void btnSave_Click(object sender, EventArgs e)
{
    if (Page.IsValid)
    {
        lblStatus.ForeColor = System.Drawing.Color.Green;
        lblStatus.Text = "Data Saved successfully";
    }
    else
    {
        lblStatus.ForeColor = System.Drawing.Color.Red;
        lblStatus.Text = "Validation Failed! Data not saved";
    }
}

Display property is supported by all validation controls

None – Error message not rendered and displayed next to the control. used to show the error message only within the ValidationSummary control

Static – The error message is displayed next to the control if validation fails. space is reserved on the page for the message although validation succeeds. The span tag is rendered with style visibility:hidden

Dynamic – The error message is displayed next to the control if validation fails. space isn’t reserved on the page for the message if the validation succeeds. The span tag is rendered with style display:none.

 

 

 



Cheap ASP.NET 4.5 Hosting

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


 

Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Tag cloud

Sign in