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:
- Cascading dropdown ( see the button Populate from action and Cascading drop down)
- Populating a table from a Partial View(see the button Add New Employee(jquery call action and render)
- How to handle error from action ( press Save 2 )
- How to send id parameters (long) from javascript to action ( press Delete 1 or Delete 2)
- 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.
I think that a featured programmer will understand fast the code . Now it’s the time for the beginner programmer.
Principles:
- 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.
- Cascading dropdowns: return a list and populate the dropdown in the request.
- To send only id – as in the url, put {. To send more data , use JSON.Stringify
- 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.
- 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
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
- Ajax Request in the server should return true or false – never return error.
- Cascading dropdowns: return a list and populate the dropdown in the request.
- To send only id – as in the url, put {. To send more data , use JSON.Stringify
- Returning PartialViews with data : the most easy way is to create an Action , send the data to this action and return a Partial View.
- 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