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

Project

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;
            Console.WriteLine(v);
            decimal? x = null;
            x += v.Value;
            Console.WriteLine(x);

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>
    <%} %>
</select>
<% if(Model.Exists(x=>x.Key ==Val) )
{
       %>
       <script type="text/javascript">
   $(document).ready(function () {

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

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") %>
        </script>
  

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>" %>

to

<%@ 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>" %>

//code

<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);
 }
 [HttpPost]
 public ActionResult FastEditEmp(BusinessLogic.Employee emp)
 {
 try
 {

 var dbid = EmployeeList.LoadFromID(emp.ID);
 UpdateModel(dbid);
 dbid.Save();
 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'
 });
 $dialog1.dialog('open');
// so the please wait dialog was shown to the user. Now load the content of the action specified in url
 $.get(url,
 {
 ID: empID
 },
 function(txt) {

 var $dialog = $('#dialog');
 $dialog.html('');
 $dialog.html(txt)
 .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();
 allInputs.remove();
 allInputs.empty();
 $(this).dialog("close");
 $(this).dialog('destroy');

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

 window.alert(ser); -- debug mode
 $(this).dialog('close');
 $(this).dialog('destroy');
//saving data by posting to same url!
 $.post(url,
 ser,
 function(text) {
 $(this).dialog("close");
 $(this).dialog('destroy');
 if (text.ok) {

 window.alert("Saved - you can change here the display id with jquery");
 window.location.reload(true);
 }
 else {
 window.alert(text.message);
 }

 }
 );

 }

 }

 });

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

}

 </script>

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 .

Asp.NET MVC and DOS – re-using the ViewModels

(Please read first : http://msprogrammer.serviciipeweb.ro/2010/03/29/asp-net-mvc-orm-and-viewmodels/ )

One of the biggest challenges in programming was write once- GUI everywhere ( Ok, ORM impedance mismatch is another story)

I mean by that re-using the logic from an application in another application. ASP.NET MVC , with the commitment to strongly viewmodels, make me think that it will be now easier to transfer the viewmodels to an console application.

Let’s see the usual Employee-Department and creation.

First the Database :

Then the ViewModel for creating an employeeand for list of employees


public class ViewModelEmployee
 {
 public static DepartmentList ListOfDepartments
 {
 get
 {
 //TODO : put this into cache to not load every time
 DepartmentList dl = new DepartmentList();
 dl.Load();
 return dl;
 }
 }
 }
 public class ViewModelEmployeeCreate : ViewModelEmployee
 {
 public Employee emp = new Employee();

 public static void SaveNew(Employee emp)
 {
 emp.SaveNew();
 }
 }
 public class ViewModelEmployeeList : ViewModelEmployee
 {
 public EmployeeList employees;
 public void Load()
 {
 employees = new EmployeeList();
 employees.Load();
 }
 }

And now the magic :

ASP.NET MVC DOS

[HttpPost]
 public ActionResult Create(Employee emp,long DepartmentID)
 {
 try
 {

 emp.Department = new Department() { ID = DepartmentID };
 ViewModelEmployeeCreate.SaveNew(emp);

 return RedirectToAction("Index");
 }
 catch(Exception ex)
 {
 ModelState.AddModelError("", ex.Message);
 return View(new ViewModelEmployeeCreate(){emp=emp});
 }
 }


Console.WriteLine("choose department");
 var listdep=ViewModelEmployee.ListOfDepartments;
 foreach (var item in listdep)
 {
 Console.WriteLine(item.ID + ")" + item.Name);

 }
 string s=Console.ReadLine();
 long DepartmentID;
 if (!long.TryParse(s, out DepartmentID))
 {
 Console.WriteLine("exit : not a long :" + s);
 return;
 }
 if (!listdep.Exists(item => item.ID == DepartmentID))
 {
 Console.WriteLine("not a valid id:" + s);
 return;
 }
 Employee emp = new Employee();
 emp.Department = new Department() { ID = DepartmentID };
 Console.Write("employee name ?");
 emp.Name= Console.ReadLine();
 ViewModelEmployeeCreate.SaveNew(emp);

Now for listing employees:

ASP.NET MVC DOS
public ActionResult Index()
        {
            ViewModelEmployeeList vmel = new ViewModelEmployeeList();
            vmel.Load();
            return View(vmel);
        }

  ViewModelEmployeeList vmel = new ViewModelEmployeeList();
            vmel.Load();
            foreach (var item in vmel.employees)
            {
                Console.WriteLine(item.Name);
            }

As you can see , the codes are really similar ( although the console application is filled with first verification and the MVC is not )

Please download the application from testaddropdownlist

To install : run the emp.sql file, change in the app.config/web.config the connection string to point to the real database/sql server.

Summary : This simple application shows how to re-use ViewModels from an ASP.NET MVC and a DOS Console Application

Homework : Add  WindowsForms application and do the same.

Andrei Ignat weekly software news(mostly .NET)

* indicates required

Please select all the ways you would like to hear from me:

You can unsubscribe at any time by clicking the link in the footer of our emails. For information about our privacy practices, please visit our website.

We use Mailchimp as our marketing platform. By clicking below to subscribe, you acknowledge that your information will be transferred to Mailchimp for processing. Learn more about Mailchimp's privacy practices here.