Chosen and Jquery and MVC

In the MVC forums I have seen a reference to Chosen. From the description here:
“Chosen is a JavaScript plugin that makes long, unwieldy select boxes much more user-friendly.”
It look beautifool – and I see the opportunity to improve my toolbox. I said: “I will do in 10 minutes”. Well, it did take longer – but not so long.

I will make an example my tutorial mvc and ajax – since it does not require any database.

So I download the source from https://github.com/harvesthq/chosen/ , put the .js in Scripts folder, the .css in Contents folder and registered in JqueryMVCRazor\JqueryMVCRazor_Web\Views\Shared\_Layout.cshtml

<link href="@Url.Content("~/Content/chosen.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/chosen.jquery.min.js")" type="text/javascript"></script>

Here is the code : ( from JqueryMVCRazor\JqueryMVCRazor_Web\Views\Shared\EditorTemplates\EditEmployeeViewModel.cshtml ):

 @{
     var idcombo = "#"+ ViewData.TemplateInfo.GetFullHtmlFieldId("cmbemp" + Model.Employee.IdEmployee);
     }<script>
     $(document).ready(function () {

         $("@idcombo").chosen({ no_results_text: "No results matched"});

     });

 </script>

And I said, this will be all.

Not so: see the picture – the names does not show up:

image

First I was thinking that it does not select the item. After several attempts, I realize the “…” ( three dots) – that means the width was not enough.
Next move, since I was in the javascript mood, was to add some javascript to adjust the width to fit:

So the code becomes:

$("@idcombo").chosen({ no_results_text: "No results matched" });
$("@idcombo").width("350");

No difference. So I tried the opposite way:

$("@idcombo").width("350");
$("@idcombo").chosen({ no_results_text: "No results matched" });

Now it matches:
image

And , thinking about a bit, it is better right in the Dropdown declaration :

@Html.DropDownList("cmbemp" + Model.Employee.IdEmployee, new SelectList(Model.DepartmentList, "IDDepartment", "NameDepartment", Model.Employee.Department.IdDepartment),new{ style="width:350px;"})

Summary:

Integration of Chosen with MVC dropdown is rather simple. Add the .js, the .css, register in the page, add $(“@idcombo”).chosen() declaration and do not forget the width of the dropdown ( select )

Source code here
Later edit: Please add also

to the header

First version of Messaging system

image

Realized the first version. When you logon on the system, the application sends you an email and you can see it.

Lots of thing done – however, the testing is not complete.

Logging was the difficult part- since I want to work with various loggers( LOG4NET, NLOG, MS TRACE, and so on). I required to a duck typing from  DeftTech. See logging assembly for more details.

You can download the files from http://messagemvc.codeplex.com/– however, you may want to wait for a NuGET version.

If you want to help me further , please send me an email via http://messagemvc.codeplex.com/.

Jquery Ajax Request and MVC detailed

I have made a post about how to configure the MVC with Razor , Partial View and returning JSON.  It does not need a database – that also because it should be simple to download and see the mechanism.

The sample demonstrates:

  1. Cascading dropdown ( see the button Populate from action and Cascading drop down)
  2. Populating a table from a Partial View(see the button Add New Employee(jquery call action and render)
  3. How to handle  error from action ( press Save 2 )
  4. How to send id parameters (long) from javascript to action ( press Delete 1 or Delete 2)
  5. How to send objects(Employee) from javascript to action ( press Save 1 or Save 2)

The PartialView is made with Razor – but this does not matter. The project can be written as well in ASPX.
asp.net mvc jquery razor cascading demo

I think that a featured programmer will understand fast the code . Now it’s the time for the beginner programmer.

Principles:

  1. Ajax Request in the server should return true or false – never return  error. The error should come from network failure or incorrect IIS server communication.
  2. Cascading dropdowns: return a list and populate the dropdown in the request.
  3. To send only id – as in the url, put {. To send more data , use JSON.Stringify
  4. Returning PartialViews with data : the most easy way is to create an Action , send the data  to this action and return a Partial View. The attempt to re-do the data from an existing DOM Element in javascript is error prone.
  5. A View page must have a ViewModel ( named Model in MVC code ) . The ViewModel can contain data from multiple classes in order to have all data that the View needs. How do you construct this ViewModel ? Simple: think about the data the View needs.

Exemplification :

1.Ajax Request in the server should return true or false – never return  error.

The _Layout in MVC should contain this :

$(document).ready(function () {
            $.ajaxSetup({
                cache: false,
                error: function (x, e) {
                    if (x.status == 0) {
                        alert('You are offline!!\n Please Check Your Network.');
                    } else if (x.status == 404) {
                        alert('Requested URL not found.');
                    } else if (x.status == 500) {
                        alert('Internal Server Error.');
                    } else if (e == 'parsererror') {
                        alert('Error.\nParsing JSON Request failed.');
                    } else if (e == 'timeout') {
                        alert('Request Time out.');
                    } else {
                        alert('Unknown Error.\n' + x.responseText);
                    }
                }
            });
        });

See as the JSON error are handled here – network, timeout, others. And in the server never return error – use this boilerplate

 [HttpPost]
        public JSonResult ....
        {
             try
            {
             var data = obtain data from the server....
   return Json(new {ok = true,mydata=data,  message = ""});
            }
            catch (Exception ex)
            {
                return Json(new {ok = false, message = ex.Message});
            }

This way, the only code returned is ok – false or true.
The javascript that call this have this form

 $.ajax({
            type:"POST",
            url:...  ,
            data: .... ,
            datatype:"JSON",
            contentType:"application/json; charset=utf-8",
            success: function (returndata) {
                if (returndata.ok) {
                    //do something with returndata.mydata
                }
                else {
//this is an error from the server
                    window.alert(' error : ' + returndata.message);
                }

            }
        }
        );

See tha handling of if (returndata.ok)
2.Cascading dropdowns: return a list and populate the dropdown in the request.

Example in code: from an department id in the first dropdown the code will fill the employees for the department
Always begin with server code .

[HttpPost]
        public JsonResult GetEmployeesForDepartment(long id)
        {
            try
            {
                //in real application made a better load / retrieving
                var emp = new employeeList();
                emp.Load();
                emp.RemoveAll(item => item.iddepartament != id);
                
                return Json(new { ok = true, data = emp, message = "ok" });
            }
            catch (Exception ex)
            {
                return Json(new { ok = false, message = ex.Message });
            }
        }

As you the first principle ( handle errors ) is applied and the data is filled and returned by

return Json(new { ok = true, data = emp, message = “ok” });

Then wrote an event( here cascadingdropdown) for the first dropdown

<select id="cmbDept" style="display:none" onchange="javascript:cascadingdropdown()"> 
</select>

Then code it

 function cascadingdropdown() {
        var idDept = $("#cmbDept").val();
        window.alert(" call cascading dropdown for iddepartment = " + idDept);
        var urlemp = '@Url.Action("GetEmployeesForDepartment")';
        var select = $('#cmbEmp');
        $.ajax({
            type: "POST",
            url: urlemp,
            data: { id: idDept },
            success: function (returndata) {
                if (returndata.ok) {

                    window.alert('employee data is on javascript,  populating combo ');
//empty the combo
                    select.empty();
//fill again 
                    $.each(returndata.data, function (index, itemData) {

                       
                        select.append($('<option></option>').val(itemData.IdEmployee).html(itemData.NameEmployee));


                    });
                    select.show('slow');
                }
                else {
                    window.alert(' error : ' + returndata.message);
                }

            }
        }
        );

    }

The filling of the second dropdown occurs on
$.each(returndata.data, function (index, itemData) {
3. To send only id – as in the url, put {. To send more data , use JSON.Stringify
The code is when you press “Save” or “Delete” . For saving we should send the Name and the department id. For Delete , just the id.
Let’s begin with delete
In server code delete Action have only the id of the employee as a parameter:

    public ActionResult DeleteEmployee(int id)
        {
//just delete it - not important code

So the client code will be simple:

function deleteEmployee(idemployee){
        window.alert('now delete ' + idemployee);
        var urlDelete = '@Url.Action("DeleteEmployee")';
        $.post(urlDelete,
            {id: idemployee}, // see here how we transmit an unique parameter
         function (returndata) 
         {
            if(returndata.ok){
                window.alert(' deleted!');
                $("#emp"+ idemployee).hide('slow');
            }
            else{
                window.alert(' error : ' + returndata.message);                
            }

        });

So you see how the
DeleteEmployee(int id)
from server code correspond with
{id: idemployee}
from the client browser.

For saving an employee we will be happy to receive the Employee class:

[HttpPost]
        public ActionResult SaveEmployee(employee emp)
        {

To receive such a parameter we will replicate employee structure in Javascript

function saveEmployee(idemployee) {
        window.alert('now save ' + idemployee);
        var urlSave= '@Url.Action("SaveEmployee")';
        var dept = $("#item_cmbemp" + idemployee).val();
        var name = $("#txtemp" + idemployee).val();
        //replicated structure as the emnployee class in server C# code
        var emp = {
            IdEmployee: idemployee,
            NameEmployee: name,
            iddepartament: dept
        };
        $.ajax({
            type:"POST",
            url:urlSave,
            data:JSON.stringify(emp),//use this in order to MVC binding to take place 
            datatype:"JSON",
            contentType:"application/json; charset=utf-8",
            success: function (returndata) {
                if (returndata.ok) {
                    window.alert(' saved ');                    
                }
                else {
                    window.alert(' error : ' + returndata.message);
                }

            }
        }
        );

    }

So you see how the class instance parameter <strong>emp from server
SaveEmployee(employee emp)
corresponds with the client browser emp structure that is stringified to send to the server

 var emp = {
            IdEmployee: idemployee,
            NameEmployee: name,
            iddepartament: dept
        };

4. Returning PartialViews with data :
Use the same Partial View that you use it for rendering an edit.

public ActionResult AddNewEmployee()
        {
            
            EditEmployeeViewModel evm = new EditEmployeeViewModel();
            evm.DepartmentList = new departmentList();
            evm.DepartmentList.Load();
            evm.Employee = new employee(0,"New !",evm.DepartmentList[0]);
            return PartialView("~/Views/Shared/EditorTemplates/EditEmployeeViewModel.cshtml", evm);//TODO: use T4MVC
        }

And javascript code:

 function AddNew() {
        var urlAdd='@Url.Action("AddNewEmployee")';
        $.get(urlAdd, function (data) {
            window.alert(' new employee coming from action !');           
            $('#tableEmp > tbody:last').after( data);//add last the whole data
        });


    }

We are using a simple get – and we have “cached” to false ( see rule 1)

4. A View page must have a ViewModel ( named Model in MVC code ) . The ViewModel can contain data from multiple classes in order to have all data that the View needs
Look at the page
asp.net mvc jquery razor cascading demo

It is clear we need the list of department( maybe cached somehow to not query all the time the database) and the employee (id, name) for each row of the table .
So this we will make:

  public class EditEmployeeViewModel
    {
        public departmentList DepartmentList{get;set;}//need the list to put in dropdown
        public employee Employee { get; set; }// the editing employee
        public EditEmployeeViewModel()
        {
            
        }
        public EditEmployeeViewModel(int id)
        {
            DepartmentList = new departmentList();
            DepartmentList.Load();
            var EmployeeList = new employeeList();
            Employee=EmployeeList.LoadId(id);
        }
         
    }

Conclusion

  1. Ajax Request in the server should return true or false – never return error.
  2. Cascading dropdowns: return a list and populate the dropdown in the request.
  3. To send only id – as in the url, put {. To send more data , use JSON.Stringify
  4. Returning PartialViews with data : the most easy way is to create an Action , send the data to this action and return a Partial View.
  5. A View page must have a ViewModel ( named Model in MVC code ) . The ViewModel can contain data from multiple classes in order to have all data that the View needs.

The download is here:
Jquery MVC Razor demo full

Transform Mozilla Bookmarks into a list

You have seen that I begin to post “friday links

It is simple , once you have SqlLite Manager add-on for FF. ( add-on, source)

Just run the following query ( for the last 7 days bookmarks) by selecting “places.sqllite”:

SELECT 
"<p><a target='_blank' href='" || moz_places.url  || "'>" || moz_bookmarks.title || "</a></p>"

FROM moz_bookmarks Inner JOIN moz_places WHERE moz_bookmarks.fk = moz_places.id AND moz_bookmarks.title != "null" 
and last_visit_date BETWEEN  strftime('%s',date('now','-7 day'))*1000000 and strftime('%s',date('now'))*1000000 
and dateAdded BETWEEN  strftime('%s',date('now','-7 day'))*1000000 and strftime('%s',date('now'))*1000000 

(OK, I must know why I multiply by 1000000  – but,hey – it works ….)

Debug Visual Studio 2010 on Windows x64 global.asax

I have Windows 7 on x64. I have installed Visual Studio on top. Besides it is a 32 edition ( as the FF ), he does not know Edit and Continue (see http://blogs.msdn.com/b/rmbyers/archive/2009/06/8/anycpu-exes-are-usually-more-trouble-then-they-re-worth.aspx )

However, I did not expect that he does not know how to debug in Application_Start . Read and found this hack : http://blogs.msdn.com/b/webdevtools/archive/2007/12/13/workaround-debugging-global-aspx-cs-application-start-with-asp-net-web-server-within-visual-studio.aspx

However, this does not work as Edit and Continue does not work.

So, after thinking a bit, I have come to another hack . There are another server that comes with Visual Studio : Cassini. I do not use this , because there are many difficulties. However, for debugging Application_Start there is very convenient:

So Project, Properties and change from IIS:

image

 

to :

image

 

That will be all. Works with WebForms and MVC.

friday links 7

  1. Introduction to PRISM – Online Training Course for .NET Developers
  2. Free Databases in the Window Azure Marketplace — Visual Studio Magazine
  3. Download: {0} – Microsoft Download Center – Download Details – Windows Azure Platform Training Kit
  4. The Secret to Success at Work: Stop Working | Psychology Today
  5. Author Guidelines – SQLServerCentral
  6. How can I display the result of a View in a popup window? : The Official Microsoft ASP.NET Forums
  7. Razor, Nested Layouts and Redefined Sections – Marcin On ASP.NET – Site Home – MSDN Blogs
  8. Convert text into PDF using ASP.NET and C# – CodeProject
  9. How to handle errors in ASP.NET MVC | jgauffin's coding den
  10. Rands In Repose: How Can I Help You?
  11. WhatsNewNET45-en.png (PNG Image, 4448×3145 pixels) – Scaled (26%)
  12. jgauffin's coding den – Thoughts and ideas about architecture and programming (in c#/.net) | jgauffin's coding den
  13. Quote by Marilyn Monroe: "I'm selfish, impatient and a little insecure. I ma…"
  14. Being IN in LINQ to SQL – Or How I learned to Love Contains (aka Getting Linq to SQL to generate a T-SQL WHERE clause that includes an IN) – Greg's Cool [Insert Clever Name] of the Day
  15. Everything SQL Server Compact: SQL Compact 3rd party tools
  16. unfinished work – I Believe In The Internet – The Content Industry Doesn't
  17. .NET Framework Libraries
  18. Founder's Blog – Jitbit: "90% of your users are idiots"
  19. Founder's Blog – Jitbit: Go Get A Cofounder [Mistakes I Made #5]
  20. Using T4 to generate Configuration classes
  21. Using T4 to Auto Generate web.config Files | Fryer Blog