Issue: Razor TextBoxFor returns null in Controller


I had a couple of textbox’s using razor syntax and some had an html attribute disabled in order to stop the user from editing. On Postback, the disabled textboxes kept on returning null. I made a couple of tests. At first I thought it is because I am setting the value in jQuery which was not the case. The problem is that the form ignors all disabled fields, even if they contain data. So the trick was to simply removed disabled and replace it with readonly.



@Html.TextBoxFor(model => model.username, new { @disabled= “disabled” })


@Html.TextBoxFor(model => model.username, new { @readonly = “readonly” })

Adding MVC Meta Tags to razor pages

In every View we can assign different meta tags (title, description, keywords, etc) however it is not very clear to every one how this is achieved. In reality this is quite easy.

So here it goes:

In your “_Layout.cshtml” paste the following in your head section:

<meta name=”description” content=”@ViewBag.Description” />
<meta name=”keywords” content=”@ViewBag.Keywords” />


Now, in your other pages which will inherit from the layout, at the very top where you usually have Viewbag.Title defined, add the following Viewbags:


ViewBag.Title = “Home Page”;
ViewBag.Description = “Welcome to Rochcass Blog”;
ViewBag.Keywords = “C# posts, errors and solutions, problem solving, css3, html5, ASP.NET, Linq, MVC, Nhibernate”;


You can do the same for other meta tags such as author, etc.





MVC Redirect from View with Parameters

I needed to redirect to another view using JavaScript for which I encountered quite some issues to do so.

1. First of all, windows.location.href = “http://&#8230;.” would not work.

2. Then I discovered that what needed to be done to redirect to another view was:

window.location.href = ‘@(Url.Action(“Index”, “Home”))’;

3. However, I needed to pass a search query and so I added the normal new parameter:

var mySearchQuery = $(“#mySearch”).val();

window.location.href = ‘@(Url.Action(“Index”, “Home”, new { search = mySearchQuery }))’;

The above kept on giving me error, no matter what I tried to put instead of mySearchQuery.

4.Finally, I found the solution for this. Which was:

var mySearchQuery = $(“#mySearch”).val();
var tempUrl = ‘@(Url.Action(“Index”, “Home”, new { search = 0, }))’;
var actualUrl= tempUrl .replace(“0”, mySearchQuery );
window.location.href = actualUrl;

Hope that helped 🙂

MVC 4.0 jquery object has no method “”

In order to help you understand the reason for this post, I will explain my initial situation. I was using .NET MVC 4.0 with razor and I needed to use some jquery plugins. I tried fancybox, tagsinput, etc etc and each plugin kept on failing to work do the error similar to “$().fancybox is not a function”. After some reseach and attempts to fix this issue, I realised that jquery was loading twice, not because I referenced it twice.

I initially looked at the _layout.cshtml page and saw that css and modernizer are being rendered by razor but since I did not see the rendering of jquery I added my own jquery reference. However razor was rendering jquery at the very bottom of the _layout.cshtml and thus jquery was being referenced twice, making plugins unusable. Razor uses the follow render syntax to reference jquery at the bottom of the page:


To fix either remove your reference at the top or if like me you have used normal jquery such as $(document).ready() etc, you will need the reference at the top and not at the bottom. In that case either remove the render from the bottom, or just drag it all the way to the head of the page.

Hope this helped 🙂

Error: NHibernate.LazyInitializationException was unhandled by user code


When using Fluent Nhibernate I have encountered several times the following exception:

NHibernate.LazyInitializationException was unhandled by user code

In my situation, the error was showing up when I try to get details from a referenced  column. For instance, from a movies table I have several columns, one of which was CategoryID. In my details view, I wanted to display CategoryName rather than CategoryId so my code looked similar to:

string Category = movie.Category.Name.toString();

That’s when the error was coming up stating that the session was closed. However, when using:

string Category = movie.Category.Id.toString();


The last example when I was getting the Id, the error was not fired since the CategoryId is within the same table and thus the session would be open. However, when attempting to get the Category Name, the session would be closed since that session was opened specifically for the movie table.


To solve this I simply modified a line of code in my mapping class where I was adding the reference and added the fetch join:


Id(x => x.Id);

References<Category>(x => x.CategoryId, “CategoryId”);


Id(x => x.Id);

References<Category>(x => x.CategoryId, “CategoryId”).Fetch.Join();

MVC Passing Parameters from one view to another through Query Strings

Pass Parameter to another view of another controller:

In view:

@Html.ActionLink(“Movies”, “Index”, “Movie”, new { CategoryId = item.Id}, null)


  • 1st par “Movies” refers to the link text visible to user
  • 2nd par “Index” is the page you want to link to in the other view
  • 3th par “Movie” is the other View folder you want to link to
  • 4th par is the actual parameter you want to pass, in this case we will be passing category Id to filter the movie list by category


In the Movie Controller where we will retrieve the Query String:

public ActionResult Index(int CategoryId)

return View(new GetMoviesByCategory(CategoryId);  //replace text in brackets with own methods or preferences.


P.S Make sure Parameters are the same (CategoryId) in both View and Controller. You can also pass and assign a parameter manually by replacing item.Id with the CategoryId for instance:

new { CategoryId = 5 }

LINQ for Nhibernate

References Required:

  • using Domain;   //this is the folder where your entities are found
  • using NHibernate;
  • using NHibernate.Criterion;

Other Requirements:

  • Nhibernate / Fluent Nhibernate
  • Linq for Nhibernate
  • Nhibernate Session Helper (can find ready ones on the internet)

1. Return a row by integer Id

public Movies GetById(intId)

using(ISession session = NHibernateHelper.OpenSession())

return session.Get<Icon>(Id);


2. Return a simple IList<> / Return all rows in a table:
public IList<Movies> GetAll()

using(ISession session = NHibernateHelper.OpenSession())

return session.CreateCriteria(typeof(Movies)).List<Movies>();


3. Return an IList<> with a WHERE clause:

public IList<Movies> GetMoviesByCategory(int CatId)

using(ISession session = NHibernateHelper.OpenSession())

return session.CreateCriteria(typeof(Movies)).Add(Restrictions.Eq(“CategoryId”, CatId)).List<Movies>();


4. Return an IList<> with a 3-way JOIN and WHERE clause

public IList<MovieImages> GetMovieImagesByMovieCategory(int CatId)

IList<Movie> movies = GetAllMovies(); //Change with your query
IList<MovieCategory> categories = GetAllCategories(); //Change with your query
IList<MovieImages> images = GetAllImages(); //Change with your query

using(ISession session = NHibernateHelper.OpenSession())

return (from mi in images
join m in movies on mi.Movie.Id equals m.Id
join c in categories on m.CategoryId.Id equals c.Id
where c.Id == category.Id
select mi).ToList<MovieImages>();


5.Convert List to IList<>

IList<MovieImages> list = myNormalList.ToList<MovieImages>(); //myNormalList would be a common List()

Simple MVC and Razor with Database Connection for Simple Insert, Update and Delete.

Model View Controller

If you are new in MVC (Model View Controller) then this tutorial is the ideal for you. I had issues in finding one single tutorial with all my questions so I decided to put one together myself. This tutorial might seem long however, most of the tutorials is full of images to help you visualize better so in order words, it is not as long as it might look like on your scroll bar 😉 Goodluck and hope you find no issues… if you do, feel free to leave a comment and I will be glad to help where possible.

Continue reading

Error: entitytype entity type has no key defined


No Primary Key is defined. Visual Studio generally looks out for an entityproperty int ID or similar and set it as a primary key. However, if our primary key is something like “Username” then we need to specify which one it is.



Include the namespace:

using System.ComponentModel.DataAnnotations;

Before your Primary Key add the following attribute: