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

Tags:

5 Comments

friday links 11

  1. Dan Ariely: How to Pay People – Businessweek
  2. Matt Wrock’s Blog | Unit Testing ASP.Net Http Handlers and a discussion of Auto Mocking and the Testable pattern
  3. Simple Producer Consumer With Tasks And .NET 4
  4. QUnit layout for JavaScript testing in ASP.net MVC3
  5. Using QUnit with Razor Layouts
  6. Don’t Call Yourself A Programmer, And Other Career Advice | Kalzumeus Software
  7. HTML5 Forms with ASP.NET MVC and MvcContrib.FluentHtml | User InExperience
  8. Licensing and Maintenance Terms – PostSharp
  9. Really silly things to do with C# expression trees | Ryan Rauh’s Blog
  10. Csajoknak! Egy ruha, tízféleképp | Nemkutya.com
  11. Home: The Official Microsoft ASP.NET Site
  12. Nadeem Afana’s blog · ASP.NET MVC 3 Internationalization
  13. Amazon.com: The Flinch eBook: Julien Smith: Kindle Store
  14. 5 ways to view documents online without signing up | Tech Tips
  15. Writing an automatic debugger in 15 minutes (yes, a debugger!) « TripleEmcoder
  16. Some guidelines for a first time MVC developer : The Official Microsoft ASP.NET Forums
  17. Dumping Objects Using Expression Trees – Paulo Morgado
  18. InfoQ: Domain Driven Design Quickly
No Comments

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/.

Tags:

4 Comments

friday links 10

 

  1. 7stacks | Alastria Software
  2. WebSequenceDiagrams.com – Draw and Edit Sequence Diagrams in seconds
  3. Custom remote Validation in MVC 3 : The Official Microsoft ASP.NET Forums
  4. jQuery Time Entry with Time Navigation Keys – Rick Strahl’s Web Log
  5. MSDN Blogs
  6. Article Viewer
  7. AutoCollage 2008
  8. Framework Design Guidelines Digest v2 – Krzysztof Cwalina – Site Home – MSDN Blogs
  9. Portable Library Tools – Visual Studio Gallery
  10. Kodu – Microsoft Research
  11. Moodle.org: Download standard packages
  12. First, Understand Your Screen « James Pearce
  13. Tyranny of the Tools
  14. 9GAG – How to Teach Yourself Programming
  15. Don’t Be A Free User (Pinboard Blog)
  16. The World According to LINQ – ACM Queue
  17. Dropdownlist with check boxes or multi-select (mvc3/jquery)? : The Official Microsoft ASP.NET Forums
  18. Chosen – a JavaScript plugin for jQuery and Prototype – makes select boxes better
  19. FUCK PASSWORDS – Blog – December 2011 – veekun: fuzzy notepad
  20. 9GAG – Trust me, I’m an engineer
  21. Custom Basic Authentication for RESTful services – Pablo M. Cibraro (aka Cibrax)
  22. InterKnowlogy Blogs » Blog Archive » ASP.NET Universal Providers
  23. Custom Basic Authentication for IIS
  24. Geek Sheet: Bare-metal backup and recovery | ZDNet
1 Comment

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

Tags: , ,

No Comments

friday links 9

  1. Razor View Engine in MVC 3
  2. Startups Are Hard. So Work More, Cry Less, And Quit All The Whining « Uncrunched
  3. Navigating OData and WCF Data Services – CodeGuru
  4. The right tool for the job | Growin’ up
  5. 10 things to love about Windows 8 | TechRepublic
  6. Open Source.NET — Visual Studio Magazine
  7. ASP.NET Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries – Scott Hanselman
  8. 9 Things That Motivate Employees More Than Money | Inc.com
  9. Easier Is Better Than Better – Smashing Magazine
  10. Asynchronous Programming – Pause and Play with Await
  11. Asynchronous Programming – Easier Asynchronous Programming with the New Visual Studio Async CTP
  12. Asynchronous Programming – Async Performance: Understanding the Costs of Async and Await
  13. ASP.NET: Prevent IIS 7.5 from overriding custom error pages with IIS default error pages | Jan Jonas’ blog
  14. T4 Templates: A Quick-Start Guide for ASP.NET MVC Developers – Web Development Tools @ Microsoft – Site Home – MSDN Blogs
  15. Free eBook – Razor View Engine in MVC 3 – Greg’s Cool [Insert Clever Name] of the Day
  16. Expression Tree Serialization – Home
  17. Why Many Developers Hate ASP.NET… and Why They’re Wrong | Nettuts+
  18. http://www.hanselman.com/blog/ScottHanselmans2011UltimateDeveloperAndPowerUsersToolListForWindows.aspx
No Comments

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 ….)

1 Comment

friday links 8

  1. FOODS
  2. LINQ Between Operator – Stack Overflow
  3. Top 10 reasons why Darth Vader was an amazing project manager – GeekWire
  4. Chess-Results Server Chess-results.com – Tournament-Database
  5. Chess This Is Sparta!!
  6. Five Absolutely Essential Utilities that make Windows better – Scott Hanselman
  7. MongoDB vs. RDBMS Schema Design
  8. How Mature Is Your Continuous Integration? « James Betteley’s Devops Ramblings
  9. UK unemployment: Meet the British bosses who say ‘give us foreign workers every time’ | Mail Online
  10. Attempting to solve the INotifyPropertyChanged problem – simoncropp’s posterous
  11. SQL Server 2012 RC News – Nick MacKechnie – Site Home – MSDN Blogs
  12. SirSQL.net – Blog – Your "Five Nines" Means Nothing To Me
  13. You Guys Are Millionaires Right? | Shifty Jelly’s blog of mystery
No Comments

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.

Tags:

No Comments

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
No Comments