All About ASP.NET and ASP.NET Core 2 Hosting BLOG

Tutorial and Articles about ASP.NET and the latest ASP.NET Core

Free Trial Web Deploy 3.5 Hosting :: ASPHostPortal.com Proudly Launches Web Deploy 3.5 Hosting

clock November 1, 2013 10:44 by author Mike

Professional web hosting provider – ASPHostPortal.com proudly announced the integration of the latest Web Deploy 3.5 in all  web hosting plans. We are the first few hosting company that provide ASP.NET hosting plan that support the brand new Web  Deploy 3.5 Hosting.


WebDeploy v3.5 is now available and there are a few features to consider in this minor release:

  1. Load Balancer Support with Session Affinity. 
  2. Encrypting web.config Settings Post-Publish.
  3. App Offline Template.
  4. Seamless integration with IIS Manager (IIS7 and above), Visual Studio (2010 and above) for creating packages and  deploying them onto a machine, both locally and remotely.
  5. Integration with WebMatrix for deploying and downloading web applications.
  6. Seamless integration with the Web Platform Installer to install community web applications simply and easily.
  7. Web application packaging and deployment.
  8. Web server migration and synchronization.
  9. Automatic backup of Web Sites before making any changes.
  10. In addition to the IIS Manager, Visual Studio 10, Web Matrix tasks can be performed using the command-line, PowerShell  Cmdlets or public APIs.

According to ASPHostPortal.com, it's Web Deploy 3.5 offerings are distinguished by their low cost, with many of the hosting  services supporting the technology being of the more expensive variety.
For more information about this topics or have any enquiries related to Web Deploy 3.5 hosting, please visit  http://www.asphostportal.com

About ASPHostPortal.com:
ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared  hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable  solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal strive to offer the most  technologically advanced hosting solutions available to all customers across the world. Security, reliability, and  performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and  performs at optimum level.



ASP.NET 4.5 Free Trial Hosting - How to Build Website Using A Simple AJAX Driven Website with jQuery + PHP

clock October 29, 2013 07:11 by author Mike

AJAX is abbrieviated from Asynchrounous javascript and XML. It's not a new technology, but the implementation of a group of technologies to achieve a seamless interaction between client and server.

Typically, xhtml and css to present the information, javascript is used to handle user interactions, and a server side language to perform the users' requests (and normally return data in XML format, in this tutorial, we won't do that), and it all is happening in the background using the Javascript XMLHttpRequest. Javascript plays a main role tie all these technologies together and create the asynchronous interaction between client ans server.

AHAH (Asynchrounous HTML and HTTP) is a subset of AJAX which is another technique, Inspite of retreiving XML, AHAH is retreiving HTML content. Both of them are basically the same, the only difference is the content it returns. Generally, most people will simply call it AJAX, but technically, we should call it AHAH. In this tutorial, AHAH is used.

The Goodies:
- Reduce connections and bandwidth to the server, images, scripts, stylesheets only need to be downloaded once
- Reduce loading timew. User doesnt have to load pages again and again, it all happens in a same page!
- Increase responsiveness and end user experiences.

The Badies:

- Browser Back button. AJAX web pages cannot connect with browser history engine. If you clicked on back button, you can't navigate those AJAX content.
- Bookmark will not work on AJAX webpages. Due to the dynamic content, you might bookmark the homepage instead of the desired page.

- Javascript is needed. To run AJAX based website, your browser need to have javascript enabled.

The Solutions:
AJAX is not a perfect technology, but some of the limitations can be overcame with some simple solutions. I found this very userful plugin called jquery.history.js. It solves Browser Back Button. For the bookmark problem, we can solve it by appending a hash value in the end of the url. For the last one - javascript, we are going to ignore it. It can be done but I want to keep this tutorial simple.
And, of course, you'll need a good web server as well, if you're hunting for a web hosting company, you can click here to read reviews about the best web hosting out there!

Requirements

You will need the following items and environment to run this script:
- Web server with PHP support - XAMPP (mac, win and linux)

- jQuery
- history.js

1. HTML

I will provide two versions of HTML code. The first one is the most basic elements you will need to get it working. And the last one is the one I created with some design
Simplified version:

<ul>
	<li><a href="#page1" rel="ajax">Home</a></li> 
	<li><a href="#page2" rel="ajax">Portfolio</a></li> 
	<li><a href="#page3" rel="ajax">About</a></li>
	<li><a href="#page4" rel="ajax">Contact</a></li>
</ul>

<div class="loading"></div>

<div id="content">
<!-- Ajax Content -->
</div>

2. CSS

This is really really simple, just have to keep the loading and content hidden

#loading {
	background: url(images/load.gif) no-repeat;
	display:none;
}
			
#content {
	font-family:arial;
	font-size:11px;
	display:none;
}

3. Javascript

I have added comments in every single lines of the code.

$(document).ready(function () {
	
	//Check if url hash value exists (for bookmark)
	$.history.init(pageload);	
	    
	//highlight the selected link
	$('a[href=' + document.location.hash + ']').addClass('selected');
	
	//Seearch for link with REL set to ajax
	$('a[rel=ajax]').click(function () {
		
		//grab the full url
		var hash = this.href;
		
		//remove the # value
		hash = hash.replace(/^.*#/, '');
		
		//for back button
	 	$.history.load(hash);	
	 	
	 	//clear the selected class and add the class class to the selected link
	 	$('a[rel=ajax]').removeClass('selected');
	 	$(this).addClass('selected');
	 	
	 	//hide the content and show the progress bar
	 	$('#content').hide();
	 	$('#loading').show();
	 	
	 	//run the ajax
		getPage();
	
		//cancel the anchor tag behaviour
		return false;
	});	
});
	

function pageload(hash) {
	//if hash value exists, run the ajax
	if (hash) getPage();    
}
		
function getPage() {
	
	//generate the parameter for the php script
	var data = 'page=' + document.location.hash.replace(/^.*#/, '');
	$.ajax({
		url: "loader.php",	
		type: "GET",		
		data: data,		
		cache: false,
		success: function (html) {	
		
			//hide the progress bar
			$('#loading').hide();	
			
			//add the content retrieved from ajax and put it in the #content div
			$('#content').html(html);
			
			//display the body with fadeIn transition
			$('#content').fadeIn('slow');		
		}		
	});
}

4. PHP

We will not go further on PHP code, this time, I'm using a basic switch to grab the content. The content for the page is being assigned to a variable called "page". And the last line, output the content.

To debug the php script, you can access it by passing data into it, for example:

http://www.someurl.com/loader.php?page=page1

It should display the content for page1. If you know about php and database, you can store the content in the database and retrieve it. Make a simple form to edit the content and BANG... you got yourself a customized content management system.

//Get the page parameter from the url
switch($_GET['page'])  {
	case 'page1' : $page = 'Page 1'; 
					break;
	case 'page2' : $page = 'Page 2'; 
					break;
	case 'page3' : $page = 'Page 3'; 
					break;
	case 'page4' : $page = 'Page 4'; 
					break;
}
echo $page;

That's it. Make sure you check out the demo and download the source code and play with it. If you have created your own, feel free to drop your link in the comment section to show off!



ASP.NET MVC 4 Hosting :: How to Make a CheckBoxList in ASP.NET MVC 4

clock October 22, 2013 08:30 by author Mike


This article will show you how to create check box list in ASP.NET MVC. Consider that we have a list consist of three properly Name, ID and IsSelected and we have to show a checkboxlist using this list. First create a model with these properties, consider a category model with three properties and a static method which will return list of model as below. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace Sample.Models
{
    public class Category
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public bool IsSelected{ get; set; }
 
        public static List<Category> getCategory()
        {
            List<Category> category = new List<Category>()
            {
                new Category() { ID =1, Name="Cat1",  IsSelected = true },
                new Category() { ID =2, Name="Cat2",  IsSelected = false },
                new Category() { ID =3, Name="Cat3",  IsSelected = true },
                new Category() { ID =4, Name="Cat4",  IsSelected = false },
                new Category() { ID =5, Name="Cat5",  IsSelected = true },
                new Category() { ID =6, Name="Cat6",  IsSelected = false },
                new Category() { ID =7, Name="Cat7",  IsSelected = true },
                new Category() { ID =8, Name="Cat8",  IsSelected = false },
            };
            return category;
        }
    }

 

}

Add a controller where a method will return a list of model to view. We have ProductCategoryController and index method which return list of model to view as below.

namespace Sample.Controllers
{
    public class ProductCategoryController : Controller
    {
        public ActionResult Index()
        {
            List<Category> model = new List<Category>();
            model = Category.getCategory();
            return View(model);
        }
    }

 

}

Add view to this controller method. In view we have model as list of category. Now to create check box list iterate through each item of model and create checkbox list as below.

@model List<Sample.Models.Category>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Category</h2>
@using (Html.BeginForm("Index", "ProductCategory", FormMethod.Post))
{
    for (int i = 0; i < Model.Count; i++)
    {
        @Html.CheckBoxFor(m => m[i].IsSelected)
        @Html.Label(Model[i].Name);
                                           
        @Html.HiddenFor(m => m[i].Name)
        @Html.HiddenFor(m => m[i].ID)
        <br />
    }
<div>  <input type="submit" value="Go!" /></div>

}

Now, it is very Interesting thing, when you create @Html.CheckBox it will create automatically a hiddenfield for this checkbox, which will use to maintain checkbox status checked or unchecked, when this list get post to model and to get complete list at controller in post method, you have to add two more hidden field for name and ID (two other properties of list) as above.

Here is post method:

[HttpPost]
public ActionResult Index(List<Category> model)
{
    // do operation on list   

 

    return RedirectToAction("Index");


ASP.NET 4.5 Hosting :: How to Password-Protect Web Pages Using .htaccess Files

clock September 13, 2013 07:34 by author Mike

A .htaccess file (pronounced ‘dot aitch tee access’ or simply ‘aitch tee access’) is aspecial configuration file used on web servers running the Apache httpd web server software. When someone visits a page that is sitting in a directory alongside, or in the same branch as, a .htaccess file then that configuration file will be loaded by the server and processed.

.htaccess files are used to reconfigure the web server without needing to restart it. These files can be used to enable or disable additional functionality and features, such as creating redirects, disabling directory listings and password protecting directories.

If you want to password protect some of your web pages, then you need to use a .htaccess file with a .htpasswd password file. This tutorial will tell you step-by-step what you need to do.


Step By Step Instructions
Let's suppose you want to restrict files in a directory called members to username memberone with password memberonepassword. Here's what to do:
1. Create a file called .htaccess in directory members that looks like this:

AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd
require valid-user


Notes
:

  • In the AuthUserFile line, replace USERNAME with your ftp username.
  • The .htaccess file must be an ASCII text document.
  • A .htaccess file can be created in any word processor but must be saved as text only.
  • IF you upload your .htaccess file via FTP, the FTP client must be set to ASCII mode for transfer.
  • For security reasons, the .htaccess file on the server cannot be seen in a directory listing. If you don't see it after uploading it, don't worry.
    Also note that AuthName can be anything you want. The AuthName field gives the Realm name for which the protection is provided. This name is usually given when a browser prompts for a password, and is also usually used by a browser in correlation with the URL to save the password information you enter so that it can authenticate automatically on the next challenge.

2. Use the htpasswd command, from your home directory, to create a password file called .htpasswd in your home directory:
SSH to your home directory. This is simply done by connecting with your SSH client and NOT entering any path, and NOT changing directories after connecting. After connecting to your home directory via SSH, enter:

# htpasswd -c .htpasswd memberone

Type the password -- memberonepassword -- twice as instructed.
3. That's the setup done. Now test by trying to access a file in the directory members; your browser should demand a username and password, and not give you access to the file if you don't enter memberone and memberonepassword.


Multiple Usernames/Passwords

If you want to give access to a directory to more than one username/password pair, follow the steps above to create the .htaccess file and to create the .htpasswd file with one user. Then, add additional users to the .htpasswd file by using the htpasswd command without the -c:

# htpasswd .htpasswd membertwo
New password:
Re-type new password:
Adding password for user membertwo


Changing Passwords

If you want to change the password for an existing user, simply issue the same command as when you added the user. You will then be prompted for a new password. For example, if the user membertwo already exists and you want to change the password, just SSH to your home directory and enter:

# htpasswd .htpasswd membertwo


Password Protecting Multiple Directories
If you want to password protect multiple directories, and allow all users access to all password protected directories, then all you need to do is put the same .htaccess file in each directory that you want to password protect.

However, if you want to password protect multiple directories, and only allow certain users access to each directory, then you can create a different password file (all in your home directory) for each password protected directory.

Let's say you have 3 different directories (members, admins, board) you want password protected, and each one has a different set of users that you want to allow access. Then just do the following:

Create three .htaccess files and put them in their appropriate directory:

AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.members
require valid-user
AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.admins
require valid-user
AuthType Basic
AuthName "Restricted access"
AuthUserFile /home/USERNAME/.htpasswd.board
require valid-user

Remember to replace USERNAME with your ftp username (in lower case).

Create three .htpasswd files in your home directory:

# htpasswd -c .htpasswd.members memberone
# htpasswd -c .htpasswd.admins adminone
# htpasswd -c .htpasswd.board boardmemberone

That's it. Now when you need to add a user to one of the directories, just issue the htpasswd command on the appropriate .htpasswd file.



ASP.NET 4.5 Hosting :: How to Writing HTTP Handler in IIS 7.5

clock September 4, 2013 05:46 by author Mike

A handler is associated with a particular type resource. It may be mapped to only a given resource. Handler mappings may also be restricted by a Http verb which means you may want to only work with GET requests ( for example if you Http handler is only supposed to send back images) or a POST request ( for example if you collect some data on the given handler).

We should code a custom Http handler if and only if the resource type to be accessed is fairly customized and is a separate entity on you system The Http response generation logic weather visible or not is very different from a regular aspx pages. In these cases it should be observed that the request should not be part of a page lifecycle.

With IIS 7.5 and beyond it is being tried that as far as possible the config definition should be available in the web.config file of an ASP.NET web site. Handlers can be configured using the IIS wizard or by directly editing the web.config file.

This article describes how handlers are to be written and configured in IIS 7.5.

Any managed http handler implements the IHTTPHandler interface.

public class TextHandler :IHttpHandler

The Http handler has a very important property IsReusable. The purpose of this property is to define if the instance of the Http handler can be shared or not. The IsReusable property should return true if and only is there is no field in the handler which can define the state. If we make IsReusable as false then the performance is slower.

bool IHttpHandler.IsReusable{
get { return true; }

}


The other method of interest is Process request, the objective of this method is to generate any valid Http response (not html response).

void IHttpHandler.ProcessRequest(HttpContext context)
{

StringBuilder htmlText = new StringBuilder();
htmlText.Append("<html>");
htmlText.Append("<title>");
htmlText.Append("</title>");
htmlText.Append("<body>");
htmlText.Append("<h1>");
htmlText.Append("Sample Text");
htmlText.Append("</h1>");
htmlText.Append("</body>");
htmlText.Append("</html>");
context.Response.Write(htmlText.ToString());
}


Configuration of Http handlers follows similar mechanism as modules. Handlers can be configured by using web.config or using the IIS manager. If you use web.config, you can use listing below.

<system.webServer>
<handlers>
<add name="TextHandler" path="*.Text" verb="*" type="TextHandler" resourceType="Unspecified" preCondition="integratedMode" />
</handlers>
</system.webServer>

In the system.webServer section add a handlers section. In this add a new handler. The name is a unique name for the handler. The path contains the path on the server. It can be wild card or an absolute path. In this example the value can be *.Text or Static.Text. The value of verb can be * or a comma separated set of verbs such as GET, POST, PUT, DELETE or any verbs used for this handler.

The type is the fully qualified name of the class in which the handler code is written. It should be noted that a precondition here is integratedMode.

If you use IIS Manager, follow steps below.

1. Open IIS Manager
2. Expand the node of your web application
3. Open the Handler Mapping feature

4.png


4. Click on Add managed handler

5.png

5. Add the various values

6.png

6. Click on request restrictions and add values for verbs

7.png

Some pitfalls

  1. Session is not available: The HttpSessionState is a module in itself hence we should ensure that when creating a module we will not have access to Http Session.
  2. Http request is read only: The various elements of the Http request such as query strings in modules are readonly. It should be noted that the url is not read only and you can create modules for Url rewrite.
  3. Http handler IsReusable: The IsReusable property is a death trap for the novice programmer. Great care should be taken to decide the value of IsReusable. It should be noted that as far as possible we should try to keep our handler stateless in interest of performance.


ASP.NET 4.5 Hosting :: Task Parallel Library Improvements (Parralel Programming)

clock August 28, 2013 06:59 by author Mike

Microsoft has introduced a new set of libraries, diagnostic tools and  runtime in .NET 4.0 to enhance support for parallel computing. The main objective of these features is to simplify parallel development, i.e., writing parallel code in a natural idiom without having to work directly with threads. Microsoft has been working on ways to improve the performance of parallel applications in .NET 4.5, specifically those using the Task Parallel Library. Here is a preview of what you can expect to see:



Task, Task<TResult>
At the core of .NET’s parallel programming APIs is the Task object. With such an important class Microsoft took great pains to ensure it is as small as possible. Most of the properties for Task are stored not in the class itself, but rather a secondary object called ContingentProperties. This secondary object is created on an as-needed basis, thus reducing the memory footprint for the most common scenarios.

When .NET 4.0 was released the most common scenario was fork-join style programming such as seen with Parallel.ForEach and Parallel LINQ. With .NET 4.5 and the introduction of async, continuation style programming takes the forefront. Microsoft is so confident that this will be the predominate style that they are moving ContinuationObject into Task and the other fields into ContingentProperties. The end result is faster continuations and a smaller Task object.

The net result was a 49 to 55% reduction in the time it takes to create a Task<Int32> and a 52% reduction in size.


Task.WaitAll, Task.WaitAny
Imagine waiting for 100,000 tasks at the same time. On an x64 machine that would introduce 12,000,000 bytes of overhead above and beyond the size of the tasks themselves. With .NET 4.5 that overhead has dropped to a mere 64 bytes. WaitAny likewise dropped from 23,200,000 bytes of overhead to 152 bytes.

This dramatic change came about due to a change in how kernel synchronization primitives are used. In previous versions one primitive was needed per task. This has been reduced to one per wait operation, regardless of the number of tasks involved.

ConcurrentDictionary

In .NET only reference types and small value types can be assigned atomically. Larger value types such as Guid require are not read and written atomically. To work around this in .NET 4.0, the node objects used by the ConcurrentDictionary are recreated each time the value associated with a key is changed. In .NET 4.5 new nodes are only created if the values cannot be atomically written.To Improve Performance, Reduce Memory Allocations.

One way to reduce memory usage is to avoid using closures. Rather than capturing a local variable inside an anonymous function, one can pass in that information to the Task’s constructor as its “state object”. Starting with .NET 4.5, Task.ContinueWith will also support state objects.

Another technique to reduce memory usage is to cache common used tasks. For example, consider a function that accepts an array and returns a Task<int>. Since the result for the empty array case will always be the same, it would make sense to cache the Task representing the empty array.

The next tip is to avoid unnecessarily “inflating” tasks. A task is inflated when something triggers the creation of its ContingentProperties object. The most common causes for this are:

  • The Task is created with a CancellationToken
  • The Task is created from a non-default ExecutionContext
  • The Task is participating in “structured parallelism” as a parent Task
  • The Task ends in the Faulted state
  • The Task is waited on via ((IAsyncResult)Task).AsyncWaitHandle.Wait()

It should be noted that task inflation isn’t necessarily a bad thing. Rather, it is something to be aware of so that one doesn’t do unnecessary things such as pass in a CancellationToken that isn’t ever used.



Reporting Service (SSRS) Hosting :: Managing SSRS Security

clock July 29, 2013 10:50 by author Mike

SQL Server 2008 Reporting Services (SRRS) is a powerful solution that enables the authoring, management, and delivery of both paper-oriented reports and interactive Web-based reports. With SQL Reporting Services, organizations can create reports to be published to the Report Server using Microsoft or third-party design tools that use Report Definition Language (RDL), an XML-based industry standard. Report definitions and resources are published and managed as Web services and users can view reports in Web-based formats or via email.

As soon as you install SSRS 2008 R2, in your server and hit http:///reports, by default the the system administrators get access to the report manager. But if you wish to let other people see the reports that you deploy, you need to explicitly provide access to these reports. Providing access to reports is very simple and can be done at an item level( report level) or a folder level.

Let’s look at a very simple example. I have installed a SSRS 2008 R2 report server, on my local machine and have created a folder called Sandbox, in which i have added a report called Hello World.

By Default all admins in the system can access this report. Lets say, we add more reports to this folder and we need to grant access to these reports.
This can be done, by clicking on Folder Settings and then clicking on security. 

 

 

Click on New role assignment. This is the place where you define your role assignments.

If you need to grant all users of your domain access, then you may need to add 'Domain\DomainUSERS' and assign appropriate roles.

There are mainly 5 types of roles, that you can assign to an user or a group.
These roles are:
a. Browser
b. Content Manager
c. My Reports
d. Publisher
e. Report Builder.

Descriptions for each of these roles are provided in the UI itself. If you wish to add just a particular user of your domain for your report, type the username and select the appropriate role for the same.

Click OK, and your security is set.



ASP.NET MVC 4 Hosting :: ASP.NET MVC Selectlist, Selectedvalue, and Dropdownlistfor

clock July 22, 2013 07:02 by author Mike

Unintuitive framework features usually end up as highly rated questions because everyone is running into the same problem with a commonly used feature. This article will be an overview of how to use drop-down lists, setting a selected item, and issues you’ll run into on a strongly typed view. The following code have been written for MVC 4.


SAMPLE MODEL

For the sake of this article, assume we have two classes, Movie and Director. In our application we want to add new movies, and select directors from a drop-down list. The classes are structured as follows.

1
2
3
4
5
6
7
8
9
10
11
12
public class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }
    public virtual Director Director { get; set; }
    public virtual int DirectorId { get; set; }
}
public class Director
{
    public int Id { get; set; }
    public string Name { get; set; }
}


HTML.DROPDOWNLIST Vs HTML.DROPDOWNLISTFOR
To add the drop-down markup to your .cshtml page you could of course simply write out a select element by hand, but then you lose out on validation. MVC provides HTML helpers for generating common HTML elements. For an HTML select element you have two choices: Html.DropDownList and Html.DropDownListFor. The difference is the way they reference the name attribute of the resulting HTML element. DropDownList takes as it’s first argument a string that will be turned into the form field. So the call

1
@Html.DropDownList("director", directorList) //assume directorList is an IEnumerable of SelectListItem to create options from


Will result in an html element that looks like this.

1
<select id="director" name="director">...</select>


The problem with this approach is if you change the name of the property on your model from ‘director’ to ‘auteur’ you won’t get compile time checking and your form will no longer work with model binding. Html.DropDownListFor was introduced in MVC 2 and allows binding to strongly typed views. The first argument should be a lambda function that returns the model property you want the control to bind to. So in our case if the view-model includes a property DirectorId we can create a drop-down list with the code

1
@Html.DropDownListFor(viewModel => viewModel.DirectorId, directorList)


Which generates the following html

 

1
2
3
<select id="DirectorId" name="DirectorId">
...
</select>


Now if we change the name of the Director property our build will break because the lambda expression will be invalid.Note that we’re using DirectorId instead of a Director object because we likely want to store the id in a foreign key.

POPULATING DROP-DOWN LIST OPTIONS
To populate a drop-down we need to pass the HTML helper an IEnumerable. This is easily created by making a SelectList object in your controller, and passing it in via a view-model.

1
2
3
4
5
6
7
8
9
10
11
12
public ActionResult Index()
{
    var directors = new Collection
        {
            new Director {Id = 1, Name = "David O. Russell"},
            new Director {Id = 2, Name = "Steven Spielberg"},
            new Director {Id = 3, Name = "Ben Affleck"}
        };
    var selectList = new SelectList(directors, "Id", "Name");
    var vm = new ViewModel {DirectorSelectList = selectList};
    return View(vm);
}


I’ve created a collection of directors and passed it into the SelectList constructor. This collection could have been queried from a database, this sample was simply for demonstration. I’ve also supplied which fields should be the drop-down value (Id) and display text (Name). If I omitted those additional parameters the ToString method would be called on the each object to generate the item.
My drop-down list now looks like this.

 

If you don’t like passing in a SelectList as part of your model you could pass in the IEnumerable and construct the SelectList in the view, but I prefer putting as little code in the view as possible.

SETTING A DEFAULT VALUE OF THE DROP-DOWN
And here is where things start falling apart. The aforementioned StackOverflow question highlighted how hard it is to set a default value on a drop-down. The problem stems from poor documentation for DropDownListFor. There is an overload that takes a fourth parameter called selectedValue which is an object to set the value. Theoretically I should be able to have the following the default to the option with an id of 3

1
var selectList = new SelectList(directors, "Id", "Name", new {id = 3});


However the first value, David O. Russell, is still selected in the view. And as good a job as he did in Silver Linings Playbook, I want to default to Ben Affleck. The problem is by using a strongly typed view, MVC is trying to bind my DirectorId field to the DirectorId property of my model. And because I didn’t populate the DirectorId field of my view-model, MVC is defaulting the drop-down to the first value.

My solution is to set the DirectorId property of the viewmodel to the value I want defaulted as follows.

1
var vm = new ViewModel {DirectorSelectList = selectList, DirectorId = 3};


Then when my view is templated the correct option is selected.



ASPHostPortal.com Proudly Announces ASP.NET MVC 5 Hosting

clock July 12, 2013 08:44 by author Mike

ASPHostPortal.com is a premiere web hosting company that specializes in Windows and ASP.NET-based hosting, proudly announces the new Microsoft product, ASP.NET MVC 5 hosting to all new and existing customers.

ASP.NET MVC 5 is the latest update to Microsoft's popular MVC (Model-View-Controller) technology - an established web application framework. MVC enables developers to build dynamic, data-driven web sites. ASP.NET MVC 5 adds sophisticated features like single page applications, mobile optimization, adaptive rendering, and more. Here are some new features of ASP.NET MVC 5:

- ASP.NET Identity
- Bootstrap in the MVC template
- Authentication Filters
- Filter overrides

“We pride ourselves on offering the most up to date Microsoft services. We're pleased to launch this product today on our hosting environment” said Dean Thomas, Manager at ASPHostPortal.com. “We have always had a great appreciation for the products that Microsoft offers. With the launched of ASP.NET MVC 5 hosting services, we hope that developers and our existing clients can try this new features.”

ASPHostPortal.com is one of the Microsoft recommended hosting partner that provide most stable and reliable web hosting platform. With the new launch of ASP.NET MVC 5 into its feature, it will continue to keep ASPHostPortal as one of the front runners in the web hosting market. For more information about new ASP.NET MVC 5, please visit http://www.asphostportal.com.

About ASPHostPortal.com:
ASPHostPortal.com is a hosting company that best support in Windows and ASP.NET-based hosting. Services include shared hosting, reseller hosting, and sharepoint hosting, with specialty in ASP.NET, SQL Server, and architecting highly scalable solutions. As a leading small to mid-sized business web hosting provider, ASPHostPortal strive to offer the most technologically advanced hosting solutions available to all customers across the world. Security, reliability, and performance are at the core of hosting operations to ensure each site and/or application hosted is highly secured and performs at optimum level.



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

 photo ahp banner aspnet-01_zps87l92lcl.png

 

Corporate Address (Location)

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

Tag cloud

Sign in