Tag: jquery

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

Jquery and multiple Ajax

I have had 2 occasions where I need to know when the ajax call have been finished:
  1. When in the beginning of page I have to load specific items that the user have been seen last time
  2. When the page was full with ajax call  – and there was also a “submit” button that should send the information (saved already ) that the user have finished entering the fields .
So – jquery have 2 methods: ajaxStart and ajaxStop.
Code:
Put 2 divs on the page :
<div id=”divWait” style=”display:none”> Please wait…</div>
<div id=”divOK” style=”display:none”> All data submitted</div>
And put this on javascript:
$(“#divWait”).ajaxStart(function() {
$(“#divWait”).show();
$(“#divOK”).hide();
});
 $(“#divWait”).ajaxStop(function() {
$(“#divWait”).hide();
$(“#divOK”).show();
});

Asp.NET MVC, Jquery and Razor – Cascading dropdown, retrieving partial views, Json send objects, handling errors

There are many blogs and other posts on using jQuery with MVC. You can find individual posts on:

·         How to send objects to an action method via JavaScript.

·         How to retrieve partial views.

·         How to handle errors.

asp.net mvc jquery razor cascading demo

I have written a sample showing how to do all of these together. The sample is written in  MVC 3 using Razor views

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)

Without further ado, this is the project . Enjoy!

Jquery MVC Razor demo full

PS: If you seems that the code is too hard, here is a more detailed explanation :http://msprogrammer.serviciipeweb.ro/2011/12/05/jquery-ajax-request-and-mvcdetailed/

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 .

jQuery Learning

learning jquery

Taking into account that Microsoft Visual Studio 2010 integrates jQuery, you might want to read about it. Of course, the first link is just http://jquery.com/.

Then recommend “Learning jQuery – Better Interaction Design and Web Development with Simple JavaScript Techniques”

A quick to learn from it about jQuery, about $ (document). Ready, Ajax with jQuery and about (developing) plug-ins. My only problem is that plug-ins mentioned are just few …

Worth reading!

Learning jQuery: Better Interaction Design and Web Development with Simple JavaScript Techniques

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.