a developer's notes – a semi-technical web development BLOG

May 15, 2015

Have Visual Studio build your MVC Views to check for errors.

Filed under: ASP.NET MVC — Duy Nguyen @ 5:41 pm
Tags: , , , ,

Step 1

Unload Project – Right click on project in solution explorer, select Unload Project.
Step 2

Edit Project – Right click and select ‘Edit Project and project XML will load in the editor window.
Step 3

Find false in Project XML file and change this to true.
Step 4

Save the Project XML file.
Step 5

Reload Project – Right click on the project and select ‘Reload Project’.

Now when Project compiles, views will also be compiled.

February 13, 2015

The request was aborted: Could not create SSL/TLS secure channel

Filed under: ASP.NET,C# — Duy Nguyen @ 10:14 am
Tags: , , , , , ,

We had some trouble with posting data with a System.Net.WebClient request. We notice that it was sporadic and couldn’t figure it out. What we found out was that some calls had SecurityProtocolType.Ssl3 and other calls didn’t specify SecurityProtocolType.

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;

SecurityProtocolType is a static class, and what ended up happening was when one call changed the SSL type, it would affect other areas of the application. We had to explicitly set the protocol type in each request.

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // or Ssl3

September 9, 2014

MVC PartialView() VS View()

Filed under: ASP.NET MVC — Duy Nguyen @ 10:36 am
Tags: , , , , ,

Use PartialViews when you want to return a view that does that need the layout.

return PartialView()

Use Views when you need to return a view that supports the layout file.

return View()

A good blog post about it can be found here.

August 28, 2014

Custom Error Pages in MVC 4

Filed under: Uncategorized — Duy Nguyen @ 11:52 am
Tags: , , , , , ,

Default solution: Use MVC HandleErrorAttribute


In MVC, by default, you will have in your Global.ascx, under Application_Start()


And in RegisterGlobalFilters, you will have…

public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
      filters.Add(new HandleErrorAttribute()); 

In your web.config, if you turn on custom errors like this…

    <!--<customErrors mode="On"></customErrors>-->
    <customErrors mode="On" defaultRedirect="myCustompage.html?"></customErrors>

customErrors mode=”On” = will turn on the default ~/Views/Shared/Error.cshtml view. (If you’re using IE, be sure to uncheck “Friendly Http Errors.” It works good but if you navigate to http://localhost/404, you will get the default yellow error screen unless you specify defaultRedirect=”myCustompage.htm”. Only then, will the application handle an internal application AND 404s, 500s, etc.

 Note: I’ve read lots of issues trying to preserve the error status code or the original stack trace


Alternative solution: Use Application_Error


You can also go the Application_Error route but will not have a backup error page if there is an error rendering the error page.

See this great blog post.


Some good other reads:



August 21, 2014

“The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.”

I keep on getting this error in Visual Studio when trying to connect to a new Secured SSL site.

“The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.”

After I installed the certificate, I was able to continue working.

Note: Also, check if Fiddler is running. It may cause issues on SSL connections.

August 5, 2014

How to Redirect user or execute Controller Action in a Custom MVC Filter

Filed under: ASP.NET MVC,C# — Duy Nguyen @ 12:41 pm
Tags: , , , , ,

MVC Filter

    public class MyFilter : ActionFilterAttribute
        public override void OnActionExecuting(ActionExecutingContext filterContext)
            // The controller will be the controller you add the filter to. Or some base controller
            var controller = filterContext.Controller as YourController;

            // Execute controller action from filter. 

            // Redirect to controller action
            filterContext.Result = new RedirectToRouteResult( new System.Web.Routing.RouteValueDictionary
                {"controller", "mycontroller"},    
                {"action", "myaction"},
                {"querystring", "?hello=true"}

            // Redirect to external url
            filterContext.Result = new RedirectResult(url);

March 21, 2014

Using jquery.validate.unobtrusive with jquery.maskedinput

Use a regular expression validator with your view model property. This regex will match “(999) 999-9999” and anything after. The input will be restricted with jquery.maskedinput to only accept valid numbers. Whether the user enters an extension or not, the regex will still get validated. We only need to valid the minimum required phone number.

Using the Data Annotation on your view model will allow the client side unobtrusive validation to work when the user enters in a phone number with the optional extension.

View Model property

[RegularExpression(@"^([(][0-9]{3}[)][ ][0-9]{3}[-][0-9]{4})(.*)$", ErrorMessage = "Phone number busted.")]
[DisplayName("Contact Phone Number")]
public string ContactPhoneNumber { get; set; }

In your view

	@Html.EditorFor(x => x.ContactPhoneNumber)
	@Html.ValidationMessageFor(x => x.ContactPhoneNumber)


if ($("input[type=tel").length > 0) {
	$("input[type=tel").mask("(999) 999-9999? ext.9999", { placeholder: " " });

	// @Html.EditorFor is used to render any inputs that need the html 5 type attributes.
	// But @Html.EditorFor, won't allow you to add a css class, so we do it here.
	$('input[type=text],input[type=tel],input[type=datetime],input[type=date],input[type=number],input[type=password],textarea,input[type=email],input[type=url],input[type=zip]').each(function (idx, item) {
		if (!$(item).hasClass('form-control')) //class only for Bootstrap styling


March 8, 2014

Jquery Validation Unobtrusive with ASP.NET MVC

Filed under: Javascript / JQuery — Duy Nguyen @ 2:46 pm
Tags: , , , , ,

Things to remember:

1. Input controls must be wrapped within a form
2. For validation messages to appear, you must have a validation message property for each input.

@Html.TextBoxFor(x => x.MyTextBox)
@Html.ValidationMessageFor(x => x.YourProperty)

3. If you want the validation message to appear immediately upon page load, you have to run this jquery method:


4. You can customize your validation message style with these css classes that you can override:

.field-validation-error span{
     color: red;

//Adds an asterisk before the message
.field-validation-error span:before{
     content: "*";

     border: 1px solid red;

Checkbox returning “true,false” from FormCollection.

Filed under: ASP.NET MVC — Duy Nguyen @ 10:46 am
Tags: , , , , , , , , , ,

If you try Request.Form[“checkbox0”], you’ll get the value “true,false” .

Just check this:

form[key].Contains("true"); //some said chrome returns "on"


You could simplify your code doing this:

var strArray = collection["YourCheckboxName"];
char[] delimiterChars = {‘,’};
string[] checkedvalue = strArray.Split(delimiterChars);
var returnValue = checkedValue.Length > 1;

If the checkbox is checked, then the array will contain 2 values, if not, only one.

February 26, 2014

Getting started with MvcSiteMapProvider with ASP.NET MVC

Filed under: ASP.NET MVC — Duy Nguyen @ 12:54 pm
Tags: , , , , ,

Here is a great site to get started with MvcSiteMapProvider. MvcSiteMapProvider provides a simple and easy way to add breadcrumb support to your MVC site.

Some tutorial links:

Note: There is a NuGet package for

    MvcSiteMapProvider MVC 4
    MvcSiteMapProvider MVC 4 Core (core library if you need to reference the library from a non MVC project such as a class library.)
    MvcSiteMapProvider MVC 5
    MvcSiteMapProvider MVC 5 Core (core library if you need to reference the library from a non MVC project such as a class library.)

If you get an error “does not contain a definition for ‘MvcSiteMap'”in the Razor view with this line…


Add in this using statement:

@using MvcSiteMapProvider.Web.Html;
Next Page »

Blog at WordPress.com.