Why the posts can not be equal

There are multiple times that I have been accused of having made the posts either too heavy, either too simple , either the code is not good, either…

I have to say that :

1. You can not follow me, if you want …

2. The reason of the posts is that I want to share my experiences with another and gather feedback.

So stick with me and please help me with what project should I start


I am trying to think about doing a open source project to experiment with various MVC / EF / WPF /and so on features.
I was thinking about

  1. Image gallery or
  2. Employee management system.

What kind of project do you think it worth the effort to implement ?
Thank you for your suggestions!

C# quiz

Fast small quiz for sunny afternoon :
What is writing at the console those lines : ( please do not use a compiler) :

            decimal? v = 100;
            decimal? x = null;
            x += v.Value;

My standard way to work with dropdown box in ASP.NET MVC – 2 steps (or 3 if you want to add long description)

I have written a small post about dropdownlist template in ASP.NET MVC here : http://msprogrammer.serviciipeweb.ro/2010/05/30/mvc-helper-templates/

I think that the dropdownlist should be explained more – aand the example will be :

First, let’s say we have Employee and Department. And we have Employee that has a field, named IDDepartment.

When edit/create a user we want to display a dropdownlist for Department in order for the user to choose the department.

Step 1 : obtain from database a list of departments and transform into List<KeyValuePair<string,string>>  – where the first string is DepartmentID and the second is Department Name.

Let’s say there is a method to do that : deptList.Values

Step 2 : display into the aspx/ascx file with List_KVP template

<%: Html.EditorFor(model => model.deptList.Values, “List_KVP”, “IDDepartment”, new { SelectedValue = Model.emp.IDDepartment })%>

Here is the weak part: the “IDDepartment” is not strongly typed. You can transform that …but it requires writing another extension. However, when you modify the code for

SelectedValue = Model.emp.IDDepartment

it is right nearby…

For reference, here is the List_KVP.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<System.Collections.Generic.KeyValuePair<string,string>>>" %>
    string Val = "",style="";
    if(ViewData.Values != null && ViewData.Values.Count > 0)
        Val = (ViewData["SelectedValue"]??"").ToString();
        style = (ViewData["Style"] ?? "").ToString();
    if (style.Length > 0)

    var id=ViewData.TemplateInfo.GetFullHtmlFieldId("") ;
    id = id + "";

<select id="<%:id %>" name="<%:ViewData.TemplateInfo.GetFullHtmlFieldName("") %>" style="<%: style %>">
    <% foreach (var val in Model)
       { %>
            <option  value='<%: val.Key %>' <%:(val.Key == Val)?"selected=selected":"" %>><%: val.Value %></option>
    <%} %>
<% if(Model.Exists(x=>x.Key ==Val) )
       <script type="text/javascript">
   $(document).ready(function () {

       $('#<%:id  %>').change();
   }     );

Oh, and if you ask how to add a description , nothing more simple :
Step1 : add to dropdown an onchange event : onchange=’javascript:funcDepartmentRetrieve(this)”
Step 2: create a java script function that retrieves the long description from the id

 <script type="text/javascript">
         <%: Html.JavaScriptFind( Model.deptList.LongDescriptionValues, "funcDepartmentLong","notfoundDepartment") %>

Step 3 : Mix the 2 javascript functions

For your reference, the code for JavaScriptFind is

 public static MvcHtmlString JavaScriptFind(this HtmlHelper hh, ICollection<KeyValuePair<string,string>> values, string Name, string NotFound)
            string s = "function " + Name + "(value){  switch(value){";
            string ret = "case '{0}' : return '{1}';" + Environment.NewLine;
            foreach (var item in values)
                //TODO : compensate for '
                s += string.Format(ret, item.Key, item.Value);
            s += string.Format("default : return '{0}' ;//+ value;"  + Environment.NewLine, NotFound);
            s += "};";//switch
            s += "}";//function
            return MvcHtmlString.Create(s);

ASP.NET MVC pass data from a view to master

One of recurring questions in MVC is how to share data between views and master. The question must be reformulated : how to share data between ACTION and master.

The short answer is : Model of the View returned from Action have to put some data to the Model of the Master

The long answer here in 4 steps

Step 1: ensuring error.aspx page works fine

a)copy \Views\Shared\Site.Master into siteerror.master( the error.aspx inherits from a specialized model)

b) change in \Views\Shared\Error.aspx

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo>" %>


<%@ Page Language="C#" MasterPageFile="~/Views/Shared/SiteError.Master" Inherits="System.Web.Mvc.ViewPage<System.Web.Mvc.HandleErrorInfo>" %>

Step 2 : make the master strongly typed :

add a ModelMaster class

public class ModelMaster
public ModelMaster()
DataFromAction = "default data";
public string DataFromAction { get; set; }

and display this data to the html of \Views\Shared\Site.Master

<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage<MasterDataFromAction.Models.ModelMaster>" %>


<h1>This is data shared from View : <%= Model.DataFromAction%></h1>

Step 3. Make the action return a strongly typed view. We will make , for example, the Index action from Home controller.

Add the ViewModelIndex class

public class ViewModelIndex :ModelMaster
public ViewModelIndex()
: base()
base.DataFromAction = "data from index";

and modify controller action and view

First Index action in \Controllers\HomeController.cs

public ActionResult Index()
ViewData["Message"] = "Welcome to ASP.NET MVC!";
ViewModelIndex vmi = new ViewModelIndex();
vmi.DataFromAction = "here comes data from index action";
return View(vmi);

Then the view :

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MasterDataFromAction.Models.ViewModelIndex>" %>

The result is here :

When do you do this things? The sooner, the better 😉

Please find attached the project

ASP.NET MVC editing fast a property

There are some moments when you want to fast edit a property ( like a status or a name) and you do not want to load the entire “Edit” form for this.More, you are in an edit formula and do not want to add a form.

So here is the solution in ASP.NET MVC  with jquery-1.4.2.min , jquery-ui-1.8.1.custom.min for a modal dialog and some controllers. The most difficult were the javascript, so I let to the final.

We will be editing the name for an employee in 4 steps.The most difficult to understand is the step 4(javascript) , however, it can be re-used with any other object- so you can put it in a common js file.

Step 1

create a view for editing the name , named FastEditEmp

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<BusinessLogic.Employee>" %>
<!-- edit inline the name -->
<%= Html.HiddenFor(Model=>Model.ID) %>
<%= Html.LabelFor(model=>model.Name) %>
<%= Html.EditorFor(model=>model.Name) %>

Step 2

Create the controllers and verify it works – at least the get  action .

public ActionResult FastEditEmp(int id)
 var emp=EmployeeList.LoadFromID(id);
 return View(emp);
 public ActionResult FastEditEmp(BusinessLogic.Employee emp)

 var dbid = EmployeeList.LoadFromID(emp.ID);
 return new JsonResult() { Data = new { ok = true, message = "succes" } };

 catch (Exception ex)
 //TODO : log
 return new JsonResult() { Data = new { ok = false, message = "error : " + ex.Message } };


Step 3
Create the hyperlink to edit the name of an employee (emp) :

<a href=’javascript:EditModal(<%= emp.ID%>,”<%=Url.Action(“FastEditEmp”,new {id=emp.ID}) %>”)’>Edit name</a>

Step 4

This is the most difficult one, the javascript. However, more of the code is common no matter what you want to edit fast modal :

var wait = '<%= ResolveUrl("~/Content/Images/wait.gif") %>';
function EditModal(empID,url)
// load a please wait dialog
 var $dialog1 = $('<div></div>')
 .html("Loading data <br /> <img src='" + wait + "'></img>")
 .dialog({ autoOpen: false,
 title: 'please wait'
// so the please wait dialog was shown to the user. Now load the content of the action specified in url
 ID: empID
 function(txt) {

 var $dialog = $('#dialog');
 autoOpen: false,
 title: 'Edit',
 modal: true,
 show: 'blind',
 hide: 'explode',
 closeOnEscape: false,
 buttons: {

 "Close": function() {
//just cleanup - no saving
 var allInputs = $(":input:not(:button)");
 var ser = allInputs.serialize();

 "Save": function() {
//now saving data : serializing and posting
 var allInputs = $(":input:not(:button)");
 var ser = allInputs.serialize();

 window.alert(ser); -- debug mode
//saving data by posting to same url!
 function(text) {
 if (text.ok) {

 window.alert("Saved - you can change here the display id with jquery");
 else {





 $dialog1.dialog('close');//closing the wait dialog
 $dialog.dialog('open'); // show main editing dialog



As always, please find here the saving modal files. Please execute first the emp.sql file, then modify the connection string into the web.config .