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

September 9, 2014

MVC PartialView VS View

Filed under: ASP.NET MVC — adevelopersnotes @ 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.

http://completedevelopment.blogspot.com/2014/01/is-there-really-no-difference-between.html

August 28, 2014

Custom Error Pages in MVC 4

Filed under: Uncategorized — adevelopersnotes @ 11:52 am
Tags: , , , , , ,

Default solution: Use MVC HandleErrorAttribute

 

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

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

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…

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

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.
http://thirteendaysaweek.com/2012/09/25/custom-error-page-with-asp-net-mvc-4/

 

Some good other reads:

http://www.devcurry.com/2012/06/aspnet-mvc-handling-exceptions-and-404.html

http://colinmackay.co.uk/2011/05/02/custom-error-pages-and-error-handling-in-asp-net-mvc-3-2/

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# — adevelopersnotes @ 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. 
            controller.SomeControllerMethod();

            // 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);
        }
    }

Preventing Browser Cache with a MVC Controller Filter

Filed under: ASP.NET MVC — adevelopersnotes @ 12:04 pm
Tags:
public class NoCacheFilter : ActionFilterAttribute, IActionFilter
    {
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.HttpContext.Response.Cache.SetExpires(DateTime.Now.AddDays(-1));
            filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
            filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
            filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            filterContext.HttpContext.Response.Cache.SetNoStore();
            filterContext.HttpContext.Response.Cache.SetAllowResponseInBrowserHistory(false);

            this.OnActionExecuting(filterContext);
        }
    }

You can declarate your controller with this filter and if the user clicks on the back button, the MVC routing will attempt to (re)retrieve data from your app.

April 30, 2014

Invoke a MVC Html Helper Method in a Unit Test

Filed under: ASP.NET MVC — adevelopersnotes @ 9:14 am
Tags: , , ,
HtmlHelper helper = null;
helper.YourHelperMethod();

April 25, 2014

jquery.validate : Unable to get property ‘getAttribute’ of undefined or null reference

Filed under: Javascript / JQuery — adevelopersnotes @ 12:31 pm
Tags: , , , , ,

I got this error recently in jquery.validate.js:
“Unable to get property ‘getAttribute’ of undefined or null reference”

Jq_ErrorAttr

GetAttributeError

Turns out the error was from a input type checkbox needing a name attribute and not just an Id attribute.

April 10, 2014

Twitter Bootstrap 3 Style DateTime Picker

Filed under: CSS / Styling,HTML — adevelopersnotes @ 9:48 pm
Tags: , , , ,

Here is a working example using eonasdan‘s version.

https://github.com/Eonasdan/bootstrap-datetimepicker

http://jsfiddle.net/QM8eC/7/

April 2, 2014

Using HTML5 Data Annotations for Zipcode and Telephone Numbers

Filed under: ASP.NET MVC,Javascript / JQuery — adevelopersnotes @ 11:22 am
Tags: , , , , , ,

Setup your view model properties with HTML 5 attributes:

[Required]
[DataType(DataType.PhoneNumber)]
public string Phone { get; set; }

[Required]
[DataType(DataType.PostalCode)]
public string ZipCode { get; set; }

Then in your script file, you can have controls use jquery.MaskedInput and also add the bootstrap css class “form-control”

    setupMaskInputs: function () {
        // Any view model property that has a [DataType(DataType.PhoneNumber)] attribute, renders type=tel
        if ($("input[type='tel']").length > 0) {
            $("input[type='tel']").mask("(999) 999-9999? ext.9999", { placeholder: " " });
        }

        // Any view model property that has a [DataType(DataType.PostalCode)] attribute, renders type=zip
        if ($("input[type='zip']").length > 0) {
            $("input[type='zip']").mask("99999?-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'))
                $(item).addClass('form-control');
        });
    }

March 30, 2014

Can’t Connect to SqlServer 2012 LocalDB

Filed under: SQL — adevelopersnotes @ 11:12 am
Tags: , , , , , , ,

I had trouble connecting my sql server to (LocalDB)\v11.0 with my Windows account. I ended up having to delete it and recreate it.

Open a cmd prompt

c:\sqllocaldb delete "v11.0"
LocalDB instance "v11.0" deleted.

c:\sqllocaldb create "v11.0"
LocalDB instance "v11.0" created with version 11.0

If the database is in use, stop MSSQL service and try again.

Next Page »

Theme: Rubric. Get a free blog at WordPress.com

Follow

Get every new post delivered to your Inbox.