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 Hosting - ASPHostPortal.com :: ASP.NET MVC vs ASP.NET - Which is better?

clock June 3, 2016 22:54 by author Dan

When developers start to build new web projects they face two options- either using ASP.NET MVC framework or ASP.NET web forms. These days, more and more companies are however choosing the MVC based framework to revise their existing sites significantly or to develop new ones. The framework has a multitude of benefits as well as technical goodies which have made it the darling among the developers.

MVC, short for Model-View-Controller is an architectural pattern that helps in division of an application into three basic components- the controller, the model and the view. This framework is a great alternative to the web forms pattern when creating applications since it is highly testable as well as lightweight presentation framework. It comes integrated with all current .NET features like authentication based on membership as well as master pages. Most developers are quite familiar with the pattern. Here is a low-down on the advantages that the MVC based framework offers over the web forms.

Separating application tasks or concerns- A huge advantage in the framework is that it clearly separates Business Logic, Data, Model, UI, test-driven development and testability. Core contracts of the framework are interface-based for which mock objects may be used for the testing. These mock objects are simulated objects imitating the behaviours of application's actual objects. The application can be unit-tested without making the controllers run, making the testing more flexible as well as fast. Any framework may be used for the testing.

Clientcaching

Silverlight makes this available to us. When we integrate Silverlight full advantage may be taken of the feature. This leads to faster application loading; in fact some part of processing may be done through web browsers, this makes the execution of client site as well as the server side a lot faster. You can even integrate JQuery and MVC so that the code written runs in browser, taking away a huge load away from the server.

HTML size

In ASP.NET there is a huge problem in the HTML size of view state as well as controls. All data rendered is stored by view state with the final result being the final HTML getting too large. For those on slow internet connections, the loading time will be slow as well as delayed. The current framework takes care of that problem since the view state concept is absent here.

Supporting ASP.NET routing

This URL-mapping component is very powerful, letting you build applications with searchable and comprehensible URLs. Through this there is no need for URLs to include extensions of file-names since the design supports patterns of URL naming and these work good enough for SEO or search engine optimization as well as REST or representational state transfer addressing.

Pluggable as well as extensible framework

The design of MVC's components makes them easily customizable or replaceable. Individual view engine, action-method parameter serialization, URL routing policy as well as other components can be plugged in. The use of DI or Dependency Injection and IOC or Inversion of Control container models is also supported. With DI you can inject objects into classes and it does not rely on class for creation of object itself. The testing is made easier by the condition imposed that when an object is required by another object then another object should be sourced from an external source like configuration file.

The biggest advantage of ASP.NET MVC platform is that it contains all the features as well as advantages of .NET since the basis is the same for both. However, some disadvantages are that understanding codes during the process of customization may not be an easy process. Another problem is the cost- the start-up costs are much higher in the MVC platform when compared to the web form based one. But looking at the benefits that are enjoyed by the developers and the end result, this is but a small price to pay for. You can get in touch with a asp.net application development company who can help you develop web apps that are stable, scalable and secure.

About ASPHostPortal.com:

ASPHostPortal.com is The Best, Cheap and Recommended ASP.NET & Linux Hosting. ASPHostPortal.com has ability to support the latest Microsoft, ASP.NET, and Linux technology, such as: such as: WebMatrix, Web Deploy, Visual Studio, Latest ASP.NET Version, Latest ASP.NET MVC Version, Silverlight and Visual Studio Light Switch, Latest MySql version, Latest PHPMyAdmin, Support PHP, etc. Their service includes shared hosting, reseller hosting, and Sharepoint hosting, with speciality in ASP.NET, SQL Server, and Linux solutions. Protection, trustworthiness, and performance are at the core of hosting operations to make certain every website and software hosted is so secured and performs at the best possible level.



ASP.Net Hosting - ASPHostPortal.com :: Solving Time View Errors in ASP.NET MVC

clock June 4, 2015 06:40 by author Dan

One of the best things about using a compiled language over a scripting language is that you get compile-time checks that prevent run-time errors later. ASP.NET MVC uses a hybrid approach by default. Views are compiled at run-time, but controllers, models, and other classes are pre-compiled. MVC also allows you to create strongly-typed views, but since those views aren’t compiled until run-time, you don’t always get warned about changes to your models (like property name changes) or other errors in your view until it’s running.

There’s a simple way to change this, though, by setting the views to build at compile time. Unfortunately this setting isn’t exposed in the Project Properties page in Visual Studio, but can still set it up manually. Here’s how:

    >> Right-click on your project file in Visual Studio’s Solution Explorer and choose Unload Project.
    >> Right-click the project file again and choose Edit YourProject.csproj.
    >> Look for a node called <MvcBuildViews> in the first <PropertyGroup> node (the one without any other attributes). If it’s not there, add it.
    >> Add or update the value inside the <MvcBuildViews> node to true. When you’re done it should look like this:

    <MvcBuildViews>true</MvcBuildViews>

    >> Save the project file changes.
    >> Right-click the project file in Solution Explorer one last time and select Reload Project.

Your views will now be built at compile -time and you will get syntax errors from any mistakes in your Razor syntax or breaking changes to your model, and you’ll get them long before your code makes it in front of users.

Keep in mind that, though, if you like to edit your .cshtml files while you’re running the debugger, these changes will no longer show up in the browser until you recompile the application again. I guess you can’t have it all!

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET MVC hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET Hosting - ASPHostPortal.com :: Solving Cannot Attach The File '.mdf' as Database in MVC

clock May 28, 2015 06:44 by author Dan

While doing database update using code-first migrations in ASP.Net MVC, came across the strange exception and details are as follows,

Issue back ground details,
1. Manually deleted auto created ".mdf" file from App_Data folder using Visual Studio.
2. Executed update-database in package manager console. Then got the below exception,

System.Data.SqlClient.SqlException (0x80131904): Cannot attach the file 'E:\Backup\Practice\MVC4\DotNetExamples\DotNetExamples\App_Data\DotnetExamples.mdf' as database 'DotnetExamples'.

at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)

at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)

at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)

at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)

at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)

at System.Data.SqlClient.SqlConnection.Open()

at System.Data.Entity.Migrations.DbMigrator.ExecuteStatements(IEnumerable`1 migrationStatements)

at System.Data.Entity.Migrations.Infrastructure.MigratorBase.ExecuteStatements(IEnumerable`1 migrationStatements)

at System.Data.Entity.Migrations.DbMigrator.ExecuteOperations(String migrationId, XDocument targetModel, IEnumerable`1 operations, Boolean downgrading, Boolean auto)

at System.Data.Entity.Migrations.DbMigrator.ApplyMigration(DbMigration migration, DbMigration lastMigration)

at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.ApplyMigration(DbMigration migration, DbMigration lastMigration)

at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)

at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)

at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)

at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)

at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()

at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()

ClientConnectionId:7c44a645-a831-418e-b8e6-88232006e97a

 
No clue about this, how to resolve and after spending lot of time searching on web, came across the following solution. Keeping this for my future reference and it might help for others for same type of problem,

Solution:

If you delete the DB file, it still stays registered with SqlLocalDB. Sometimes it fixes it by deleting DB. We can do this from the command line.

Open the "Developer Command Propmpt for VisualStudio" under your "Start/Programs menu->All Programs->Visual Studio 2012->Visual Studio Tools"

    Run the following commands:

    sqllocaldb.exe stop v11.0

    sqllocaldb.exe delete v11.0


Now execute "update-database" command from package manager console and it will create database for you without any obstacles.

Best ASP.NET Hosting Recommendation

ASPHostPortal.com provides its customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. ASPHostPortal.com offers ASP.NET MVC hosting starts from $1/month only. They also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable ASP.NET Hosting, ASPHostPortal.com should be your best choice.



ASP.NET MVC Hosting - ASPHostPortal.com :: Donut Caching with ASP.NET MVC 6

clock January 14, 2015 06:03 by author Ben

I'm working on a new personal project during my free time and I chose to develop it with ASP.NET MVC 6 (hosted on ASPHostPortal of course...) to test the new features of this version. In this project, I need to display "Logged in as xxxx " (if the user is logged...) in the header of the page. This is a simple scenario to implement but caching could complicate the development of my web app...



My header is in my layout and is used everywhere but I would like to place an OutputCacheAttribute on some actions (the home page, etc.). If I put the attribute on an action, all of my users will see an header with "logged in as xxxx" of the first incoming query!

The solution to this problem is named "Donut Caching": you send a cached page from the server with a "fresh" portion which is not in cache (the donut's hole).
Concretely, the server does not generate the requested page (query the DB, etc.): it just needs to take the cached version and replace a specific part.

Luckily, you do not need to develop your own custom OutputCacheAttribute because there is already a very good package (There's An App A Pack For That... thanks NuGet!): MvcDonutCaching for ASP.NET MVC 3 and later...

To install the package, you can search through NuGet or directly type the following command in the "Package Manager Console":

install-package MvcDonutCaching

The use of this package is very simple... They have created several extension methods for HtmlHelper with the usual parameters plus another boolean parameter: excludeFromParentCache. I just have to call my partial view (with the "connected has xxxx"...) like that:

@Html.Action("LoginHeader", "Account", new { lang }, true)\

The last parameter of Html.Action is set to true: this partial view will be excluded from the parent cache (if there is a cache on the action...). (do not pay attention to new { lang }, it's a route's value) To make it work, you must not use the OutputCacheAttribute but the DonutOutputCacheAttribute:

[DonutOutputCache(Duration = 60, VaryByParam = "lang")]
     public ActionResult Index(string lang)
     {
         ...
     
         return View();
     }

And that's it! The first request will be cached during 60 seconds but the LoginHeader partial view will be generated every time.

(note: of course, the donut caching only works on the server side...)

Best Hosting for Your ASP.NET MVC Hosting

Following reviewed for Best ASP.NET hosting companies that help with ASP.NET MVC, ASPHostPortal is Best ASP.NET Hosting Recommendation for ASP.NET MVC. They give 99,99% uptime assured, as well as 30 Days Money back assured, superb customer service, and many more.



ASP.NET MVC Hosting - ASPHostPortal.com :: How to Structure The Application in ASP.NET MVC Areas

clock November 25, 2014 05:11 by author Ben

This week I discovered a difficulty related to structuring an ASP.NET MVC web applications one advancement crew was dealing with. The things they have been trying to do was quite straightforward: to create a folder framework each having their particular subfolders for View/Controller/Scripts/CSS and so on. The appliance assets like JS/CSS etc. were not getting rendered properly. The difficulty was owing to NET.config file lying underneath the subfolder, which when moved to the Views folder below that subfolder things went good. The purpose of this post just isn't to debate regarding the specifics of that difficulty and it is solution.But to discuss regarding how we will very easily framework our ASP.NET MVC Web application as per distinct modules, which is an clear need for just about any big application.


ASP.NET MVC follows the paradigm of “Convention Over Configuration” and default folder structure and naming conventions operates good to get a smaller sized software. But for relatively bigger a single there is a necessity to customise.The framework also offers adequate provisions for the same.You'll be able to have your personal controller manufacturing facility to get custom methods to making the controller classes and custom see engine for finding the rendering the sights. But when the necessity would be to structure the applying to distinct subfolders as per modules or subsites I believe using “Area” in ASP.NET MVC will likely be useful to make a streamlined software.

You can add a area to some ASP.NET MVC undertaking in Visual Studio as shown beneath.

Here I have added an area named “Sales”. As shown in the figure below a folder named “Areas” is created with a subfolder “Sales”. Under “Sales” we can see the following

  • The standard folder of Models/Views/Controllers
    • A Web.config under the Views folder. This contains the necessary entries for the RazorViewEngine to function properly
  • A class named SalesAreaRegistration.

The code (auto generated) for the SalesAreaRegistration class is shown below:

public class SalesAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "Sales";
        }
    }
 
    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Sales_default",
            "Sales/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

System.Web.Mvc.AreaRegistration may be the summary base class use registering the places to the ASP.NET MVC Web Application. The method void RegisterArea(AreaRegistrationContext context) must be overriden to sign up the realm by providing the route mappings. The class System.Web.Mvc.AreaRegistrationContext encapsulates the mandatory information (like Routes) required to sign-up the area.

In Global.asax.cs Application_Start occasion we must RegisterAllAreas() technique as demonstrated under:

AreaRegistration.RegisterAllAreas();

The RegisterAllAreas method looks for all types deriving from AreaRegistration and invokes their RegisterArea method to register the Areas.

Now with the necessary infrastructure code in place I have added a HomeController and Index page for the “Sales” area as shown below.

I have to change the Route Registration for the HomeController to avoid conflicts and provide the namespace information as shown below:

public static void RegisterRoutes(RouteCollection routes)
{
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional },// Parameter defaults
                new String[] { "AreasDemo.Controllers" }
            );
}

Now I will add a link to the Sales area by modifying the _Layout.cshtml as shown below:

<li>@Html.ActionLink("Sales", "Index", "Home", new { area="Sales"},null)</li>

Here I am navigating to the area “Sales” from the main application so I have to provide area information with routeValues. The following overload is being used in the code above:

public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes);



ASP.NET MVC SignalR Hosting - ASPHostPortal.com :: Create a Real-Time Message Board Making use of ASP.Net MVC 5, SignalR 2, and KnockoutJS

clock October 28, 2014 06:05 by author Ben

Have you ever questioned how Facebook sends you notifications the instant you receive a new information, friend request, or remark? Does the customer constantly look for new events? Doesn’t that consume a whole lot of memory within the user’s side? What sort of pressure does that place on Facebook’s servers?


 

Due to HTMl five as well as the support of web sockets in modern browsers, this performance can be achieved with out over-taxing the user or even the server. Leveraging a library like SignalR for .NET or Socket.IO for Node.js, most of the very hard perform around working with web sockets is already completed to suit your needs.

On this tutorial, we’re planning to build a real-time concept board, very similar to Facebook. Although this will not be something you should model and drive to manufacturing as-is, it could supply you with the fundamental groundwork for creating your own personal real-time net application.

Let's Start

Start the Project - Initial, begin a new ASP.Net MVC 5 project from Visual Studio 2013. You can title it what ever you want, but I named the undertaking “MessageBoardTutorial”. Make sure you place a checkmark close to "Web API".


Get dependencies with NuGet - Let’s go on and get downloading our required libraries out of the best way. We can get every thing with NuGet, saving us plenty of your time. Within the Remedy Explorer, right-click around the project name and click on “Manage NuGet Packages…” from the context menu.

Initial, you'll want to update all the packages presently set up to their newest variations. Be aware that because MVC 4, all the MVC libraries are bin deployed, so you will need to update them when commencing a fresh undertaking. On the still left, simply click on “Updates->nuget.org” and also you will see each of the offers that must be up-to-date. Just click on on “Update All” and allow NuGet do its thing.


When that's done, near the window. Open up the Package Supervisor Console in Tools > NuGet Package Manager > Package Manager Console. We must set up a few a lot more deals for this tutorial. Run the subsequent commands to set up the deals we need for this tutorial.

PM> Install-Package EntityFramework
PM> Install-Package Microsoft.AspNet.SignalR
PM> Install-Package Moment.js
PM> Install-Package KnockoutJS

NuGet will put in several dependencies that SignalR 2 needs. Additionally, you will get yourself a good tiny readme.txt. Feel free to read this, but we are going to be covering this listed here also.

The Front End

We are going to now truly commence coding. The Layout - First, we've got to go into the structure file and simplify issues somewhat - we don't truly require the responsive menu for this tutorial. Open /Views/Shared/_Layout.cshtml. It ought to now search such as this, assuming you failed to modify the default directories:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
</head>
<body>
    <div class="container body-content">
        @RenderBody()
    </div>
 
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
</body>
</html>

Edit the Home Controller and Index View - We will only need a single controller and view for this software. Inside the Remedy Explorer, open Controllers > HomeController and take away all Steps except for Index.

Now, open up the Index check out and just delete every thing. If you are a neat freak like me, truly feel totally free to eliminate another views inside the Views > Home.

Edit the View - Under is the see for your application. In case you are new to KnockoutJS, a few of this may appear unfamiliar. I will clarify a lot more when we get to the JavaScript inside the up coming section. Just be aware that wherever the thing is a "data-bind" attribute, the component is joined into a JS worth we are tracking with Knockout.

We're mostly using regular CSS courses from Bootstrap. Bootstrap gives us a quick way to incorporate a responsive grid framework for our view. The still left column includes our "login" type and also the proper the information board itself.

@{
    ViewBag.Title = "Land of Ooobook";
}
 
<div class="jumbotron">
    <h1>Land of Ooobook</h1>
    <p>Candy Kingdom's Social Network</p>
</div>
 
<div class="container">
    <div class="row">
        <div class="col-md-4">
            <form class="pad-bottom" data-bind="visible: !signedIn(), submit: signIn">
                <div class="form-group">
                    <label for="username">Sign In</label>
                    <input class="form-control" type="text" name="username" id="username" placeholder="Enter your userame" />
                </div>
                <button type="submit" class="btn btn-primary">Sign In</button>
                <br />
            </form>
 
            <div data-bind="visible: signedIn">
                <p>You are signed in as <strong data-bind="text: username"></strong></p>
            </div>
        </div>
        <div class="col-md-8">
            <div data-bind="visible: notifications().length > 0, foreach: notifications">
                <div class="summary alert alert-success alert-dismissable">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
                    <p data-bind="text: $data"></p>
                </div>
            </div>
 
            <div class="new-post pad-bottom" data-bind="visible: signedIn">
                <form data-bind="submit: writePost">
                    <div class="form-group">
                        <label for="message">Write a new post:</label>
                        <textarea class="form-control" name="message" id="message" placeholder="New post"></textarea>
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>
            </div>
 
            <ul class="posts list-unstyled" data-bind="foreach: posts">
                <li>
                    <p>
                        <span data-bind="text: username" class="username"></span><br />
                    </p>
                    <p>
                        <span data-bind="text: message"></span>
                    </p>
 
                    <p class="no-pad-bottom date-posted">Posted <span data-bind="text: moment(date).calendar()" /></p>
 
                    <div class="comments" data-bind="visible: $parent.signedIn() || comments().length > 0">
                        <ul class="list-unstyled" data-bind="foreach: comments, visible: comments().length > 0">
                            <li>
 
                                <p>
                                    <span class="commentor" data-bind="text: username"></span>
                                    <span data-bind="text: message"></span>
                                </p>
                                <p class=" no-pad-bottom date-posted">Posted <span data-bind="text: moment(date).calendar()" /></p>
                            </li>
                        </ul>
 
                        <form class="add-comment" data-bind="visible: $parent.signedIn, submit: addComment">
                            <div class="row">
                                <div class="col-md-9">
                                    <input type="text" class="form-control" name="comment" placeholder="Add a comment" />
                                </div>
                                <div class="col-md-3">
                                    <button class="btn btn-default" type="submit">Add Comment</button>
                                </div>
                            </div>
                        </form>
                    </div>
                </li>
            </ul>
        </div>
    </div>
 
</div>
 
@section scripts {
    <script src="~/Scripts/moment.js"></script>
    <script src="~/Scripts/jquery.signalR-2.0.3.min.js"></script>
    <script src="~/signalr/hubs"></script>
    <script src="~/Scripts/knockout-3.1.0.js"></script>
    <script src="~/Scripts/board.js"></script>
}

Add a bit of CSS - We have a few custom CSS classes on top of what Bootstrap provides. Currently, /Content/Site.css is in your style bundle. Open it and replace everything above the validation helper classes with this:

.pad-bottom {
    margin-bottom: 10px;
}
 
.no-pad-bottom {
    margin-bottom: 0;
}
 
.new-post {
    background-color: #c9e0fc;
    padding: 15px 10px;
}
 
.username {
    font-weight: bold;
    color: #ff6a00;
}
 
.commentor {
    font-weight: bold;
    color: #004bff;
}
 
.posts li .date-posted {
    font-size: 12px;
    font-style: italic;
}
 
.posts li {
    border-bottom: 1px solid #CCC;
    padding: 15px 0;
}
 
.posts li:first-child {
    border-top: 1px solid #CCC;
}
 
.posts .comments {
    background-color: #efefef;
    margin-top: 10px;
    padding: 10px;
    padding-left: 30px;
}
 
.posts .comments li {
    padding-top: 10px;
    border: 0;
}
 
form.add-comment  {
    margin-top: 10px;
    margin-bottom: 10px;
}

The JavaScript

Create a script - In the Scripts directory, make a new script called board.js. This script will contain the client-side logic for the application.

Edit the script - Let's begin with our script.

A message board is made of posts and comments to those posts. Let's define those objects.

var post = function (id, message, username, date) {
    this.id = id;
    this.message = message;
    this.username = username;
    this.date = date;
    this.comments = ko.observableArray([]);
 
    this.addComment = function (context) {
        var comment = $('input[name="comment"]', context).val();
        if (comment.length > 0) {
            $.connection.boardHub.server.addComment(this.id, comment, vm.username())
            .done(function () {
                $('input[name="comment"]', context).val('');
            });
        }
    };
}
 
var comment = function (id, message, username, date) {
    this.id = id;
    this.message = message;
    this.username = username;
    this.date = date;
}

A submit has an observable variety of remarks. This enables it in order that when new remarks come in, it's immediately displayed within the view.

We've outlined our submit and remark objects. Now let's define our view design that is the glue from the application.

var vm = {
    posts: ko.observableArray([]),
    notifications: ko.observableArray([]),
    username: ko.observable(),
    signedIn: ko.observable(false),
    signIn: function () {
        vm.username($('#username').val());
        vm.signedIn(true);
    },
    writePost: function () {
        $.connection.boardHub.server.writePost(vm.username(), $('#message').val()).done(function () {
            $('#message').val('');
        });
    },
}
 
ko.applyBindings(vm);

We have an observable array of posts (which have an observable array of remarks). We even have an observable assortment of notifications, which inform customers of latest posts or comments on their posts. Our view model tracks the username and if a user is signed in. Finally, a view design can include techniques.

Next, we've a way for loading posts, which is known as when the web page hundreds and the user connects into a SignalR hub. The posts are loaded from the Net API controller which we are going to make later. Each and every submit is additional to the observable assortment of posts. Each and every from the post's feedback are added to the comments observable variety of the submit. This really is a really verbose method of performing this, but I wanted to make it distinct what was happening right here.

function loadPosts() {
$.get('/api/posts', function (data) {
    var postsArray = [];
    $.each(data, function (i, p) {
        var newPost = new post(p.Id, p.Message, p.Username, p.DatePosted);
        $.each(p.Comments, function (j, c) {
            var newComment = new comment(c.Id, c.Message, c.Username, c.DatePosted);
            newPost.comments.push(newComment);
        });
 
        vm.posts.push(newPost);
        });
    });
}

The rest of the script has to do with SignalR connections and methods. We'll get back to that later. Below is the entire board.js script.

var post = function (id, message, username, date) {
    this.id = id;
    this.message = message;
    this.username = username;
    this.date = date;
    this.comments = ko.observableArray([]);
 
    this.addComment = function (context) {
        var comment = $('input[name="comment"]', context).val();
        if (comment.length > 0) {
            $.connection.boardHub.server.addComment(this.id, comment, vm.username())
            .done(function () {
                $('input[name="comment"]', context).val('');
            });
        }
    };
}
 
var comment = function (id, message, username, date) {
    this.id = id;
    this.message = message;
    this.username = username;
    this.date = date;
}
 
var vm = {
    posts: ko.observableArray([]),
    notifications: ko.observableArray([]),
    username: ko.observable(),
    signedIn: ko.observable(false),
    signIn: function () {
        vm.username($('#username').val());
        vm.signedIn(true);
    },
    writePost: function () {
        $.connection.boardHub.server.writePost(vm.username(), $('#message').val()).done(function () {
            $('#message').val('');
        });
    },
}
 
ko.applyBindings(vm);
 
function loadPosts() {
    $.get('/api/posts', function (data) {
        var postsArray = [];
        $.each(data, function (i, p) {
            var newPost = new post(p.Id, p.Message, p.Username, p.DatePosted);
            $.each(p.Comments, function (j, c) {
                var newComment = new comment(c.Id, c.Message, c.Username, c.DatePosted);
                newPost.comments.push(newComment);
            });
 
            vm.posts.push(newPost);
        });
    });
}
 
$(function () {
    var hub = $.connection.boardHub;
    $.connection.hub.start().done(function () {
        loadPosts(); // Load posts when connected to hub
    });
 
    // Hub calls this after a new post has been added
    hub.client.receivedNewPost = function (id, username, message, date) {
        var newPost = new post(id, message, username, date);
        vm.posts.unshift(newPost);
 
        // If another user added a new post, add it to the activity summary
        if (username !== vm.username()) {
            vm.notifications.unshift(username + ' has added a new post.');
        }
    };
 
    // Hub calls this after a new comment has been added
    hub.client.receivedNewComment = function (parentPostId, commentId, message, username, date) {
        // Find the post object in the observable array of posts
        var postFilter = $.grep(vm.posts(), function (p) {
            return p.id === parentPostId;
        });
        var thisPost = postFilter[0]; //$.grep returns an array, we just want the first object
 
        var thisComment = new comment(commentId, message, username, date);
        thisPost.comments.push(thisComment);
 
        if (thisPost.username === vm.username() && thisComment.username !== vm.username()) {
            vm.notifications.unshift(username + ' has commented on your post.');
        }
    };
});

The Data Layer - We will be making use of Entity Framework as well as the Code First sample for our straightforward info layer.

Inside the Models directory, develop a brand new C# class referred to as MessageBoard.cs. Our data designs are little, and in our scenario we'll just place them in a single file alongside with all the data context.

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Linq;
using System.Web;
 
namespace MessageBoardTutorial.Models
{
    public class MessageBoardContext : DbContext
    {
        public DbSet<Post> Posts { get; set; }
        public DbSet<Comment> Comments { get; set; }
    }
 
    public class Post
    {
        [Key]
        public int Id { get; set; }
        public string Message { get; set; }
        public string Username { get; set; }
        public DateTime DatePosted { get; set; }
        public virtual ICollection<Comment> Comments { get; set; }
    }
 
    public class Comment
    {
        [Key]
        public int Id { get; set; }
        public string Message { get; set; }
        public string Username { get; set; }
        public DateTime DatePosted { get; set; }
        public virtual Post ParentPost { get; set; }
    }
}

Although the actual database doesn't yet exist, it will likely be produced if the application deems it essential. Should you maintain your internet.config unchanged, it's going to develop it within your LocalDB instance of SQL Server Specific.

The API

The script requirements a technique to get in touch with to get the posts to the concept board. Whilst we could just tack a technique on to our HomeController that would try this, we can equally as effortlessly create an ASP.Web Internet API controller which will fetch and immediately convert the posts into a JSON format.

Create the API Controller - In the Solution Explorer, right click on the Controllers directory and click on Add > Web API Controller Class (v2) in the context menu. Add a new Web API controller and call it PostsController.cs

Write the API
- Replace the code with the below. Our API will simply return a JSON or XML-serialized array of all of the posts and comments on the message board when a client calls http://[yoursite]/api/posts.

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;
    using MessageBoardTutorial.Models;
 
    namespace MessageBoardTutorial.Controllers
    {
        public class PostsController : ApiController
        {
            private MessageBoardContext _ctx;
            public PostsController()
            {
                this._ctx = new MessageBoardContext();
            }
 
            // GET api/<controller>
            public IEnumerable<post> Get()
            {
                return this._ctx.Posts.OrderByDescending(x => x.DatePosted).ToList();
            }
        }
    }
</post></controller>

Handle circular references - If you look at our data models, a Post contains a virtual collection of comments, and a Comment contains a virtual Post that refers to the comment's parent. This circular reference will freak out Web API's serialization method. To solve this, just add the following line of code to the Register method in the WebApiConfig class located at App_Start/WeApiConfig.cs
   
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =
    Newtonsoft.Json.ReferenceLoopHandling.Ignore;

Circular references will now be ignored.

Implementing the SignalR Hub

SignalR provides a relationship between clientele and also the server. Clients connect to a SignalR Hub. The Hub can then contact client-side occasions on a single, some, or all related clients. The Hub tracks which consumers are linked to it. This can be the center of real-time net programs. Within our case, a client generates a fresh submit or comment, which phone calls a method around the Hub. The Hub then calls a method on all of the message board's connected users that inserts the brand new submit or remark.

In a nutshell, the awesomeness of SignalR is that it may call JavaScript capabilities on any browser linked to it. The outdated assemble is clientele could only get in touch with server-side features. This type of functionality could only be achieved via long-polling (a customer working an infinite loop that calls a server method).


Newer browsers connect to hubs via HTML 5 web sockets. For older browsers, there are long-polling and "forever frame" fallbacks.

Map the hubs - In order for SignalR to begin and for the web application to map the connection hubs, we must create an OWIN startup class. Lucky for us, this just involves a couple of clicks and a line of code. Right-click on the solution and add a new item. Find the OWIN Startup Class template. Name this file "Startup.cs". Now, you just have to add one line of code in the Configuration method to map the hubs.

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
 
[assembly: OwinStartup(typeof(MessageBoardTutorial.Startup))]
 
namespace MessageBoardTutorial
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
}

Create the Hub - Make a new directory in the root of your project called Hubs. Now, right-click on this new directory and click on Add > New Item... in the context menu. Create a new SignalR Hub Class called BoardHub.cs.


Replace the code in the file with the below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using MessageBoardTutorial.Models;
 
namespace MessageBoardTutorial.Hubs
{
    public class BoardHub : Hub
    {
        public void WritePost(string username, string message)
        {
            var ctx = new MessageBoardContext();
            var post = new Post { Message = message, Username = username, DatePosted = DateTime.Now };
            ctx.Posts.Add(post);
            ctx.SaveChanges();
 
            Clients.All.receivedNewPost(post.Id, post.Username, post.Message, post.DatePosted);
        }
 
        public void AddComment(int postId, string comment, string username)
        {
            var ctx = new MessageBoardContext();
            var post = ctx.Posts.FirstOrDefault(p => p.Id == postId);
 
            if (post != null)
            {
                var newComment = new Comment { ParentPost = post, Message = comment, Username = username, DatePosted = DateTime.Now };
                ctx.Comments.Add(newComment);
                ctx.SaveChanges();
 
                Clients.All.receivedNewComment(newComment.ParentPost.Id, newComment.Id, newComment.Message, newComment.Username, newComment.DatePosted);
            }
        }
    }

}

The Hub contains a method for writing a new post and a method for writing a new comment. Both methods are called from the client and ultimately call client-side methods for connected users.

For example, the writePost client-side method is called when a user writes a new post:

writePost: function () {
    $.connection.boardHub.server.writePost(vm.username(), $('#message').val()).done(function () {
        $('#message').val('');
    });
},

This method calls the WritePost method on the Hub. After the new post is added to the database, the Hub then calls the receivedNewPost method on all connected clients.

Clients.All.receivedNewPost(post.Id, post.Username, post.Message, post.DatePosted);

From BoardHub.cs

hub.client.receivedNewPost = function (id, username, message, date) {
    var newPost = new post(id, message, username, date);
    vm.posts.unshift(newPost);
 
    // If another user added a new post, add it to the activity summary
    if (username !== vm.username()) {
        vm.notifications.unshift(username + ' has added a new post.');
    }
};

From board.js

The Hub sends info about the new submit to this client method, which then helps make a brand new Publish JavaScript object and adds it to the starting from the view model's posts observable array. This new post is instantaneously displayed for all related customers since Knockout is observing this array. A brand new notification can also be produced for all customers other than the creator of the new publish.

Adding a remark follows the same pattern, although the client callback method differs marginally:

hub.client.receivedNewComment = function (parentPostId, commentId, message, username, date) {
    // Find the post object in the observable array of posts
    var postFilter = $.grep(vm.posts(), function (p) {
        return p.id === parentPostId;
    });
    var thisPost = postFilter[0]; //$.grep returns an array, we just want the first object
 
    var thisComment = new comment(commentId, message, username, date);
    thisPost.comments.push(thisComment);
 
    if (thisPost.username === vm.username() && thisComment.username !== vm.username()) {
        vm.notifications.unshift(username + ' has commented on your post.');
    }
};

The ID of the parent post of the comment is sent to the client, which then adds the new comment to the comments observable array of the post

Finally, let us run this point

Now you can construct and operate the project! Ooo is in dire need of a social community.

Go on and open up two browser windows and "log in" as a various person on every. Recognize how once you include a submit in a single window, it instantaneously is additional towards the other window in addition to a notification. Now, the Ice King can annoy princesses on-line too! Effectively, possibly that is not all that good.




ASP.NET MVC 4.0 Hosting with ASPHostPortal :: How To Save Email from External Login in ASP.NET MVC 4.0 with SimpleMembership

clock January 9, 2014 06:16 by author Ben

ASP.NET MVC 4 web application allows users to log in from an external provider, such as Facebook, Twitter, Microsoft or Google and then integrate into your web application. Some OAuth/OpenId providers like Facebook, Google allow to access email. This article explains how to save the email in your database.

Before implementing, first lets consider following points:
1. User name is different from Email.
2. Email might be different for different providers.
3. Email is optional(some external provider like twitter doesn’t allow to access email).

 

Getting Started:
1. Create a new ASP.NET MVC 4 --> Internet Application Project
2. Open App_Start --> AuthConfig.cs, uncomment the external services which you want to use and pass proper parameters. In this article, we will use Facebook,Twitter and Google providers.

OAuthWebSecurity.RegisterTwitterClient(
        consumerKey: "xxxx",
        consumerSecret: "xxxxxxxx");
    OAuthWebSecurity.RegisterFacebookClient(
        appId: "yyyy",
        appSecret: "yyyyyyyy");
    OAuthWebSecurity.RegisterGoogleClient();


3. In Account Model, add Email property in RegisterExternalLoginModel class:

public class RegisterExternalLoginModel
   {
       [Required]
       [Display(Name = "User name")]
       public string UserName { get; set; }
       public string ExternalLoginData { get; set; }
       public string Email { get; set; }
   }

4. To add Email field in OAuthMembership table, add following class:

[Table("webpages_OAuthMembership")]
   public class OAuthMembership
   {
       [Key, Column(Order = 0), StringLength(30)]
       public string Provider { get; set; }
       [Key, Column(Order = 1), StringLength(100)]
       public string ProviderUserId { get; set; }
       public int UserId { get; set; }
       [StringLength(100)]
       public string Email { get; set; }
   }


5. add OAuthMembership in Userscontext

public class UsersContext : DbContext
    {
        public UsersContext()
            : base("DefaultConnection")
        {
        }
        public DbSet<UserProfile> UserProfiles { get; set; }
        public DbSet<OAuthMembership> OAuthMemberships { get; set; }
    }

It will create the required structure in database when you run the application and open register page first time.

Controller Changes:
In AccountController, To set email from the external provider, replace the following lines in ExternalLoginCallback method :

// User is new, ask for their desired membership name
string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;ViewBag.ReturnUrl = returnUrl;
return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });


with the following lines:

// User is new, ask for their desired membership name
               string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
               ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
               ViewBag.ReturnUrl = returnUrl;
               var model = new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData };
               switch (result.Provider) {
                   case "facebook":
                   case "google":
                       {
                           model.Email = result.UserName;
                           model.UserName = "";
                           break;
                       }
                   case "twitter":
                       {
                           model.Email = "";
                           model.UserName = result.UserName;
                           break;
                       }
                   default:
                       break;
               }
               return View("ExternalLoginConfirmation", model);

Facebook and Google provide email as user name, so email is assigned for these providers.

In ExternalLoginConfirmation view, add following Email in form:

@Html.HiddenFor(m => m.Email)

It will post Email also when form is submitted. In ExternalLoginConfirmation method, To save email for new user,replace the following lines:

// Insert name into the profile table
            db.UserProfiles.Add(new UserProfile { UserName = model.UserName });
            db.SaveChanges();
            OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);
            OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
            return RedirectToLocal(returnUrl);

with these lines:

// Insert name into the profile table
                       user = new UserProfile { UserName = model.UserName };
                       db.UserProfiles.Add(user);
                       db.SaveChanges();
                       OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName);                                           
                       if (!String.IsNullOrEmpty(model.Email)) {
                           var oauthItem = db.OAuthMemberships.FirstOrDefault(x => x.Provider == provider && x.ProviderUserId == providerUserId && x.UserId == user.UserId);
                           if (oauthItem != null) {
                               oauthItem.Email = model.Email;
                               db.SaveChanges();
                           }
                       }
                       OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie: false);
                       return RedirectToLocal(returnUrl);

This will save email in database for new user. Now if same user wants to add other external provider then in ExternalLoginCallback method, replace following line

OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);

with following lines:

OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
               if (result.Provider == "facebook" || result.Provider == "google")
               {
                   using (UsersContext db = new UsersContext())
                   {
                       UserProfile user = db.UserProfiles.FirstOrDefault(u => u.UserName.ToLower() == User.Identity.Name);                     
                       if (user != null)
                       {                         
                               var oauthItem = db.OAuthMemberships.FirstOrDefault(x => x.Provider == result.Provider && x.ProviderUserId == result.ProviderUserId && x.UserId == user.UserId);
                               if (oauthItem != null)
                               {
                                   oauthItem.Email = result.UserName;
                                   db.SaveChanges();
                               }                         
                       }
                   }
               }

That's the tutorial How To Save Email from External Login in ASP.NET MVC 4.0 with SimpleMembership. If you're looking for best Windows ASP.NET hosting, ASP.NET MVC 4.0 hosting, cloud hosting, and SharePoint hosting, please feel free to visit http://ASPHostPortal.com. Come to the website to know more details.

 



ASP.NET MVC Hosting - ASPHostPortal.com :: Making Your Existing ASP.NET MVC Web Site Mobile Friendly

clock September 26, 2013 05:58 by author Ben

This article will show you the basic mobile features of ASP.NET MVC 4.0. We will make the following changes using CSS and ASP.NET to an existing web site to make it more user-friendly on mobile devices: 

  • Content will fit the small screen 
  • One-direction scrolling either horizontally or vertically but not both 
  • Clean and efficient design 
  • An option to visit the desktop site 


The following is a collage of the various desktop views for the Contact controller.

Responsive Design and Mobile Views

As we saw above, the application uses the default ASP.NET MVC Template. This template uses responsive design techniques using the viewport meta-tag to pick up appropriate CSS styles. The view-port is specified in _Layout.cshtml. It essentially sets the device-width reported by the browser as the width of the content frame.



Using the CSS Media queries in the Site.css, the browser switches UI based on the width of the device


As we can see above, the Media query defines a set of CSS style for width up to 850 pixels. Any width lesser than 850px is considered a mobile view in the default CSS.

With the Responsive Design in place, if we look at the site on a Mobile device, this is how it looks

Except for the Index page, the rest are usable but they look out of place or retro-fitted.

Adding First Class Mobile Support using jQuery Mobile

Now that we’ve seen the limitations for Responsive CSS, let’s explore dedicated Mobile Views and the special MVC ViewSwitcher.

- From Package Manager Console, install the jQuery.Mobile.Mvc package as follows

PM> install-package jQuery.Mobile.MVC

- This installs a host of things including jQuery Mobile UI Themes, a new Configuration file called BundleMobileConfig, a new Controller called ViewSwitcherController, an empty Context file called AddingMobileSupportToMVCContext, _Layout.Mobile.cshtml and _ViewSwitcher.cshtml.


The _ViewSwitcher.cshtml checks if the browser is Mobile browser or not and generates an appropriate link to switch views. ViewSwitcherController uses the value passed to it when user clicks on the View Switcher link and switches to the appropriate view. We’ll see what we mean by Appropriate View in the next section.

_Layout.Mobile.cshtml

As we saw, this partial view was added when we added the jQuery Mobile package. The .Mobile convention is baked into MVC and when the GetOverriddenBrowser().IsMobileDevice returns true, MVC goes and checks for .Mobile.cshtml files and starts rendering them as available. So if you only have the _Layout.Mobile.cshtml and no Index.Mobile.cshtml in your view folder, MVC will fall back on the standard Index.cshtml view while using the _Layout.Mobile.cshtml as the default layout.

This is a VERY powerful mechanism we’ve got here.

It’s worth noting .Mobile is not hardcoded, rather the default. We can have .WP7, .WP8, .Iphone, .Android or any such specially targeted views as we deem required.

With the ViewSwitcher and _Layout.Mobile.cshtml in place, now if we run the application, the Home page and Edit page look as follows. Note only the underlying _Layout page has changed to _Layout.Mobile. No new views have been introduced.

 



ASP.NET 4.5 Hosting - How to Leverage the .NET 4.5 Model Binding and Strongly Typed Data Controls with Telerik’s ASP.NET AJAX Controls

clock May 15, 2013 10:58 by author Ben

The new release of RadControls for ASP.NET AJAX includes a ton of great new features and capabilities. This post is the second of two posts I will do over the week that elaborates on the new ModelBinding support and Strongly Typed Data Controls into the Telerik’s Ajax suite. In the previous part you learned how the Strongly Typed Data Controls work and how to select data and bind the controls via the ModelBinding capabilities available in .NET 4.5. Now you will learn how to do filtering, perform CRUD operations and validate user input when you use ModelBinding.

 

Model Binding Filtering
In order to filter the data source of the data bound control and pass the filtered data to the control you could pass filter parameters to use the SelectMethod. You could get these parameters from query string, cookies, form values, controls, viewstate, session and profile. For example:

public IQueryable<Product> GetProducts([Control("RadComboBoxCategories")] int? categoryID, [QueryString]string name)
{
    // Filter the data source based on categoryID and ProductName
}

The code snippet above will get the name parameter from the QueryString and integer value of the selected item of the Telerik’s ASP.NET ComboBox with ID equlas to “RadComboBoxCategories”.

Model Binding CRUD operations
Editing
In order to have editing enabled into the data bound controls, you need to set the UpdateMethod of the corresponding control to the web form page’s method. The UpdateMethod can have following signature:

public void UpdateProduct(int ProductID)
{
    Product updatedProduct = context.Products.Where(p => p.ProductID == ProductID).First();
   TryUpdateModel(updatedProduct);
   if (ModelState.IsValid)
   {
       context.SubmitChanges();
   }
}

Where the “ProductID” is one of the fields set as DataKeyNames of the corresponding bound control. 
Or you could use following signature:

public void UpdateProduct(Product product)
{
    Product updatedProduct = context.Products.Where(p => p.ProductID == product.ProductID).First();
    TryUpdateModel(updatedProduct);
    if (ModelState.IsValid)
    {
         context.SubmitChanges();
    }
}

Inserting
In order to have inserting enabled into the data bound controls you need to set the InsertMethod property of the corresponding control to the name of the web form page’s insert method. The InsertMethod can have following signatures:

public void InsertProduct(Product p)
{
     if (ModelState.IsValid)
     {
      context.Products.InsertOnSubmit(p);
      context.SubmitChanges();
     }
}

//OR

public void InsertProduct()
{
   Product pr = new Product();
   TryUpdateModel(pr);

    if (ModelState.IsValid)
    {
                context.Products.InsertOnSubmit(pr);
               context.SubmitChanges();
    }
}

Deleting
In order to have deleting enabled into the data bound controls you need to set the DeleteMethod property of the corresponding control to the name of the web form page’s delete method. The DeleteMethod can have following signature:

public void DeleteProduct(int ProductID)
{
   Product deletedProduct = context.Products.Where(p => p.ProductID ==
ProductID).First();
    context.Products.DeleteOnSubmit(deletedProduct);
    context.SubmitChanges();
}

ModelBinding Validation
Due to the fact that Model Binding system in Web Forms supports model validation using the same validation attributes from the System.ComponentModel.DataAnnotations you could use validation into our databound controls. You could decorate properties from your model classes with the attributes provided in System.ComponentModel.DataAnnotations namespace. For example if you have DataContext mapped to a Northwind database “Product” table and you want to ensure that when inserting new product or update existing one the ProductName field is populated, you could set [Required] attribute to it into the DataClasses.designer.cs file:

[Required]
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ProductName", DbType="NVarChar(40) NOT NULL", CanBeNull=false)]
public string ProductName
{
     get
     {
           return this._ProductName;
     }
     set
     {
           if ((this._ProductName != value))
           {
           this.OnProductNameChanging(value);
           this.SendPropertyChanging();
           this._ProductName = value;
           this.SendPropertyChanged("ProductName");
           this.OnProductNameChanged();
           }
      }

Then when values from databound control editors are submitted to the server the the Web Forms Model Binding system will track whether any of these validation rules are violated in the page's ModelState property.

public void InsertProduct(Product p)
{
     if (ModelState.IsValid)
     {
           context.Products.InsertOnSubmit(p);
           context.SubmitChanges();
     }
}

To show any validation errors you could use asp:ValidationSummary control or asp:ModelErrorMessage:

<asp:ValidationSummary runat="server" ID="ValidationSummary1" />

Please note that even the model binding is a powerful feature included into the bound controls there are still some limitation.

Conclusion
With Model Binding support into our controls developing new application is never be as easy as it is now.  Please do not hesitate to download the RadControls for ASP.NET AJAX and try the model binding feature.



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