How to make a div/span at the bottom right of a div with CSS

You need to set the parent container to relative. When the position is relative, everything that will be under the container with the position to absolute will be absolute to the relative parent.

.parent 
{ 
  position: relative; 
}

.child 
{ 
 position: absolute; 
 bottom: 0; 
 right:0;
}

From here, if you create a child inside the parent container, the child will be at the bottom of the parent.

<div class="parent">
<p>This is the parent container</p>
<br/><br/><br/>
<p>This is the parent container</p>
<br/><br/><br/>
<br/><br/><br/>
<span class="child">Last line at the bottom</span>

An absolute div (or any other element) relative to the first relative parent. In the case that no element has been marked something else than the static (like to relative) than the first element will be used which is the Html element.

cssBottomRight

You can see the result in action with JSFiddle here.

Jquery selector Parent vs Closest to search element through upper levels of hierarchical structure

With JQuery you can use Parent, Parents and Closest to search element at a higher level of the one selected. What are the differences?

JQuery Parent selector

Parent() will search one level up only. For example here is the html code of a situation where you can see two level deep of div and a paragraph.

<div class="parent1">;
    <div class="parent2">;
      <p>;Hello Again</p>;
    </div>;
</div>;

If we use the Parent selector on the paragraph it will select parent2 division.

$("p").parent().css("background", "yellow");

You can see this example in action here : http://jsfiddle.net/C5Shz/

Even by specifying the class of the second level, nothing will be selected.

$("p").parent('parent1').css("background", "yellow");

You can see the result : http://jsfiddle.net/L953U/

The reason is that parent go only one level up.

JQuery Parents selector

Parents will return an array of elements. It returns all element from root to the selected element.

$("p").parents('div').css("background", "yellow");

This return 2 divisions, the parent1 and the parent2. The reason is that the parent1 is the root parent and parent2 is the parent between the selected one (p) and the searched element.

You can see the example in action here : http://jsfiddle.net/u7SaF/

JQuery Closest selector

closest() looks up the tree like .parent() but stop when the search is found. It return a single element or nothing is nothing is found.

$("p").closest("div").css("background", "blue");

This will color in blue the closest division from the p.

Here is the example in action. http://jsfiddle.net/ZNQ5Q/

If we summarize everything in bullet point:

Parent:
– Begins with the current element and go only one level up
– The returned jQuery object contains zero or one element
– The returned jQuery object contains zero or one element
Parents:
– Begins with the parent element
– Travels up the DOM tree but return element in reverse
– The returned jQuery object contains zero, one, or multiple elements
Closest:
– Begins with the current element
– Travels up the DOM tree until it finds a match for the supplied selector
– The returned jQuery object contains zero or one element

Finally, I often see code with multiple parent() called. For example, $(“p”).parent().parent()..css(“background”, “blue”). Instead, you can use eq with parents.

<div>;
    <div>;
        <div>;
           <p>;Hello Again</p>;
         </div>;
    </div>;
</div>;
$("p").parents().eq(2).css("background", "blue");

This will get all parents and since the order are from the parent selection the list will return the level up. Do not forget that the index your provide start with 0 which is the immediate parent element. In the example above, only the first div will have a background blue while the two inner divisions will remain white.

Here is the example in action.

How with JQuery to disable click until animation done

You may want to animate something before doing an action and remove the possibility to the user the press again. This is often a desired behavior because it might broke the current animation or simply doing nothing which will lead the user in a false impression of bug.

The solution is to disable the button (or link) during the animation.

function clickFunction(obj) {
    //If animated than we wait the animation to be over
    if ($(':animated').length) {
        return false;
    }

    obj.animate({
            //Animation here that is executed one but if clicked before
            //this one is over won't be reached
            }, 4000);
}

The above code work with JQuery framework and check if the animated queue contain any element. If yes, the function called by the click return false and doesn’t do anything. In fact, you could here write something to the screen if you want to inform the user that something is occurring and that he should wait.

What is the role of the Viewstart file in an Asp.Net MVC?

Since version 3.0 of the Asp.Net MVC framework, you can use the ViewStart file inside the View folder. You can use it inside your area (inside the views of your area) and also have multiple ViewStart file within the View folder if your views contain sub directory.

The ViewStart files are read from the root of the view folder to the more deep folder of the view called. So, if you are using an area which have several folder for different view, you can have a ViewStart inside the “Views” folder and one inside the “Views/Folder1”. Asp.Net MVC will read the ViewStart from the “Views” folder and then the one inside “Views/Folder1”.

An other characteristic of the ViewStart is that this one is called “_ViewStart.cshtml”. It must start with an underscore and use the .cshtml extension.

The role is to avoid to repeat some code that must be the same between views. For example, the layout for the view (the master page). Instead of defining the the top of each view what layout to use, you can simply define a layout at the root of your views folder a file _ViewStart.cshtml and put :

@{
    Layout = &quot;~/Views/Shared/_MasterPage.cshtml&quot;;
}

If you need a different layout for a specific view, simply set the layout inside the view or inside a ViewStart inside the folder of the view. Since the order of read is from the root of the Views folder to its subdirectory, this last ViewStart will set the Layout property and override the one defined previously.

If you are getting an exception saying something about cast like the following error it’s because you are using the ViewStart outside the Views folder.

Unable to cast object of type ‘ASP._Page_Areas_Admin__ViewStart_cshtml’ to type ‘System.Web.WebPages.StartPage

From there, you are limited about what you can do. But, you have access to the ViewContext.TempData which let you set variable values which can be validated in further level. For example, you can set something at the root of the ViewStart and redefine, or add if it’s a list, data in a further level. At the end, in the Layout you could read the TempData and act in consequence.

In real life, I have used once the ViewStart with a TempData to set Javascript file name that needed to be loaded but not for 2 folders. In those ViewStart, the entry was removed. In the master page, the TempData was read and the Javascript loaded. You can get more information about this real life example here.

From here, you should be able to understand that the ViewStart is a way to don’t repeat yourself between views. You should also understand that not only the ViewStart inside the view folder of the view is executed but all ViewStart in the path of your view from the root to your view is executed.

Validation with ViewModel

This post won’t explain how to do it with enterprise pattern but will focus of some solutions available to validate your Model/ViewModel with Asp.Net MVC. This article won’t focus of the advantage to use ViewModel instead of directly use Model object to the view. The article will show you how to validate your view model without having to repeat yourself in several place with your validation. We want to respect the DRY concept which specify that we should never repeat our self.

First of all, Asp.Net MVC will call the data annotation and if the class inherit from IValidatableObject the method Validate. The problem as you can see is that the ViewModel which is bound to the controller doesn’t have data annotation, neither inherit from IValidatableObject. Also, the mapping from the View Model to the Model occurs later in the process. This mean that we will need to manually call the validation to trigger the validation process which has been done to the view model.

Second, the error which are associated to properties may not be link directly by the model to the view model. For example, your view model may have a property FullName which use the FirstName and LastName property. During the validation process, if an error occur on FirstName or LastName, the error will be associated to those property name and not FullName. This result that the error won’t be displayed around the control in the view.

They are several solution. The easiest is to only display errors in the summary. We simply need to set ExcludePropertyErrors to false in the summary.

@Html.ValidationSummary(false)

By default, if no parameter is provided, the value is also false. So, you do not need to explicitly write false. Here is the ValidationExtensions.cs code for the two methods.

        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper) {
            return ValidationSummary(htmlHelper, false /* excludePropertyErrors */ ); 
        } 

        public static MvcHtmlString ValidationSummary(this HtmlHelper htmlHelper, bool excludePropertyErrors) { 
            return ValidationSummary(htmlHelper, excludePropertyErrors, null /* message */);
        }

A second solution is to map the property from the model to the view model.

ScottGu has a post that contain a helper class that does the job.

public static class ControllerExtensions
{
	public static bool TryValidateAndTranslate(this Controller controller, object model, string prefix, object propertyMap)
	{
		return TryValidateAndTranslate(controller, model, prefix, new RouteValueDictionary(propertyMap));
	}

	public static bool TryValidateAndTranslate(this Controller controller, object model, string prefix, RouteValueDictionary propertyMap)
	{
		ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() =&gt; model, model.GetType());

		foreach (ModelValidationResult validationResult in ModelValidator.GetModelValidator(metadata, controller.ControllerContext).Validate(null))
		{
			var propertyName = CreatePropertyName(validationResult.MemberName, prefix, propertyMap);
			controller.ModelState.AddModelError(propertyName, validationResult.Message);
		}

		return controller.ModelState.IsValid;
	}

	private static string CreatePropertyName(string memberName, string prefix, RouteValueDictionary propertyMap)
	{
		string propertyName = null;
		object output = null;
		if (propertyMap.TryGetValue(memberName, out output))
			propertyName = String.Format("{0}.{1}", prefix, output.ToString());
		else
			propertyName = String.Empty;

		return propertyName;
	}
}

From there, you need to call the TryValidateAndTranslate method. The method will loop all validations associated to the object which can be data annotation validation or validation written inside the Validate method of IValidatableObject. The ModelValidator.GetModelValidator method is in fact used by the framework when you are using TryValidateModel.

The usage of this method should be inside the method of the controller where the form is posted. Just after the mapping from the ViewModel to the Model.

{
//... action method

//... map view model to model

if (!this.TryValidateAndTranslate(
                 modelObject, 
                 "ModelClassName", 
                 new { FirstName = "FullName", Property2 = "Property2" }))
            return View(viewModel);

//... else return where you want to go when everything is without error
}

If something is wrong, we display the view again with the view model, otherwise, we redirect to the list view or to any view you want where no error is found. As you can see, last parameter let you specify that the validation on FirstName property should be mapped to FullName. Of course, a better approach would be to setup in a central place all those mapping. The example is really just informative because you should try to map those property with something like AutoMapper and reuse the mapping from it.

How to rebuild the database from Entities with Membership table

If you are using Entity Framework with the membership, you may come into situation where you need to rebuild your database because you are changing your models. In that case you want to also have the membership tables back when you are rebuilding your database. Here is a way to do it.

First of all, you need to open the Package Manager Console. This console will open a console where you will be able to write command to the Entity Framework Migration Tools.

packagemanagerconsole

The primary command to be used is “Update-Database”. In fact, I always prefer to use “Update-Database -Verbose -Force”

The verbose option let you see all operations that are done which can be helpful in case of problem. The force will drop all table instead of altering them. This can be useful in situation where the structure change a lot.

Unity Life time management

When you use Unity to get an instance of a class, Unity pass through the life time manager. The life time manager responsibility is indicate to unity how to instance the class into an object. This one may already have an instanced object for the class requested and thus give this one instead of creating a new instance.

TransientLifetimeManager

TransientLifetimeManager is the default life time manager used by Unity if none is specified. This is the simplest form of life time manager. It creates a new instance every time unity need an instance of the class.

var container = new UnityContainer();
container
    .RegisterType(typeof(IMyClass), typeof(MyClass), "namedMyClass")
    .RegisterType(typeof(IMyClass), typeof(MyClass), "named2MyClass", new TransientLifetimeManager());

In the above example, you can see two registrations with unity of IMyClass interface with the concrete implementation of MyClass. Both of them are using the TransientLifetimeManager. The first one is implicit because it use the default life time manager, while the second is explicit by having a third parameters which specify to use TransientLifetimeManager life time manager.

Singleton

The singleton is pattern (or anti-pattern) that specify that only one instance will live in memory. With Unity, the singleton life time manager is called ContainerControlledLifetimeManager. The ContainerControlledLifetimeManager will instance on the first call the class into an object and all subsequent call will simply give a pointer (reference) to the same object.

var container = new UnityContainer();
container
    .RegisterType(typeof(IMyClass), typeof(MyClass), "SingletonMyClass", new ContainerControlledLifetimeManager());

Of course, it’s only possible to use the explicit registration for singleton since the implicit would create a TransientLifetimeManager. A small note before we pass to the next life time manager : if you are using a web application, beware that the object will be shared between all your users.

Others life time manager

Unity does have multiple others life time manager like PerThreadLifetimeManager or PerResolveLifetimeManager. Both of them won’t be discuss there. The first one can be useful with a system where you are using parallel operations and the last one in some custom case where the life time manager need to be re-created every time.

In a web application, the default life time, TransientLifetimeManager, is the one to use. It will create an instance per web request. Of course, ContainerControlledLifetimeManager is also used in the case of instancing the data access layer, the caching system, the logging system, etc. Those are used across the system without containing “user” objects.