Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Wednesday, January 22, 2014

Pass Complex JavaScript Object to MVC Controller

In this tutorial I'm going to illustrate how we can pass complex javascript objects to MVC controller.

I have two Model objects called Project and Employee as below.

    public class Project
    {
        public long ProjectID { get; set; }
        public string ProjectName { get; set; }
    }

    public class Employee
    {
        public string Code { get; set; }
        public string Name { get; set; }
    }

And I have view-model called "ProjectViewModel" which contains above models as below.

    public class ProjectViewModel
    {
        public Project Project { get; set; }
        public IList<Employee> EmployeeList { get; set; }
    }
Now I'm going to pass instance of ProjectViewModel and an Employee object to my MVC controller. Here is the controller method.
        [HttpPost]
        public ActionResult Create(ProjectViewModel projectViewModel, Employee anotherEmployee)
        {
            return Content("done");
        }
This is the JavaScript code that we can use to call the controller method.
        var projectViewModel = {};

        var project = {};
        project.ProjectID = 1234;
        project.ProjectName = "Test Project";

        projectViewModel.Project = project;

        var employeeList = [];

        var employee1 = {};
        employee1.Code = "1111";
        employee1.Name = "Saranga";

        var employee2 = {};
        employee2.Code = "2222";
        employee2.Name = "Rathnayaka";

        employeeList.push(employee1);
        employeeList.push(employee2);

        projectViewModel.EmployeeList = employeeList;

        var employee3 = {};
        employee3.Code = "3333";
        employee3.Name = "Test User";

        $.ajax(
  {
      url: 'Project/Create',
      data: JSON.stringify({projectViewModel : projectViewModel, anotherEmployee : employee3}),
      contentType: 'application/json',
      dataType: 'json',
      type: 'POST',
      success: function (data) {
          alert("success");
      },
      error: function () { alert('error'); }
  });

Saturday, February 20, 2010

Form Validation and Suggestions using JQuery & PHP

In this post I’m going to describe about a practical use of my previous article JQuery AJAX. Here I’m going to discuss how to validate a form and how to add auto suggests to a form using JQuery and PHP.

Download Source (Password : sara)

In the above I have given you the source code of the whole project which saves the collected data to a MySQL database. It is good if you have a basic knowledge about JavaScript and PHP to understand the codes. You can learn them very easily by referring w3schools.

Since this I’m using PHP and MySQL in the above project, you have to run the code in a server like XAMP or WAMP. In this example I’m going to illustrate with WAMP. If you have the downloaded source code, you can see a folder called "jquery_form" and within that you can find folders css,js,scripts and images. Also you can see a file called index.php.

First thing you have to do is copy the "jquery_form" folder to your WAMP server’s "www" folder. Then open the "dbc.php" file inside the "scripts" folder and change its attributes. If you already haven’t a database called "userdata" and you haven’t given a password for root account, you don’t need to make any changes.

<?php
$host = "localhost";
$dbname = "userdata";
$username = "root";
$password = "";
?>

Now do the following things when the WAMP server started. I’ll also mention the result of the given action here.

1. First run the "sql.php" file located in the "scripts" folder. The only thing you need to do is give the address to the file in the address bar. E.g. http://localhost/jquery_form/scripts/sql.php. This should be done when the first time you run the project.

I wrote this file to create a MySQL database with one table and needed fields to store the collected data. If you didn’t make changes to "dbc.php" file, there will be a databased called "userdata" and table called "details_user".

2. Then run the "index.php" file and fill the form correctly and submit. You will see your data in the database. If you try to give the same login name again, you will see the suggestions related to the name and birthday.

Let’s see the codes and check how we can add validation and suggestions. Here the JavaScript which do the above task is "validation.js" which is located in "js" folder. I’ll put the real line numbers in following piece of codes as they appear in actual file.

<title>JQuery Ajax Form | Saranga Rathnayake</title>

<!-- CSS -->
<link rel="stylesheet" href="css/styles.css" type="text/css"/>
<link type="text/css" href="css/jquery-ui-1.7.2.custom.css" rel="stylesheet" /> 

<!-- JavaScript -->
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
<script src="js/validation.js" type="text/javascript"></script>
<script type="text/javascript">
 $(function(){
  $('#datepicker').datepicker({
   dateFormat:'dd/mm/yy',
   changeMonth: true,
   changeYear: true,
   yearRange: '-90:+0',
   maxDate: '+0'
  });
 });
</script>
</head>
<div id="container">
<form id="logform" name="logform" class="logform" method="post" action="" >
<?php if(

Above lines are from the "index.php" file, there I have linked necessary CSS and JavaScipt files. You can see a JavaScipt code which use to DatePicker.

//On blur
 name.blur(validateNameAndSuggest);
 iname.blur(validateIName);
 address.blur(validateAddress);  
 email2.blur(validateEmail);
 nic.blur(validateNIC);
 phno.blur(validatePhNo);
 email.blur(validateLoginEmailAndSuggest); 
 imgveri.blur(validateImg); 
 
 // on changed
 bday.change(validateDOB);
 
 //On key press
 //name.keyup(validateName);
 //iname.keyup(validateIName); 
In the above lines I have called the validation functions in "blur" and "keyup" events. I have commented the "keyup" events, if you want them you can uncomment. Then I’ll show you how the validation works.
function validateNIC(){
  var a = $("#nic").val();
  var filter = /^[0-9]{9}[v|V]$/;
  if(filter.test(a)){
   nic.removeClass("error");
   nicInfo.text("");
   nicInfo.removeClass("error");
   return true;
  }
  //if it's NOT valid
  else{
   nic.addClass("error");
   nicInfo.text("Type a valid NIC please, format: xxxxxxxxxV");
   nicInfo.addClass("error");
   return false;
  }
 } 

In the above code I have use Regular Expressions to make the validation more easier. If the Regular Expression dose not match with the input, then I have changed the CSS Class of the text box which change its color. And also I have added some information about the error. Then let’s see how suggestions work.

function suggestLogginName(){
  
  var name = $("#fname").val();
  var bday = $("#datepicker").val();
  
  if(validateName() && validateDOB()){
   $.post("scripts/isValiedName.php",  { loginName:name, birthday:bday,suggestion:"OK" },
     function(data){
     emailInfo.html(data);
   }); 
  }

 } 

The above function calls if the entered login name exist in the database. It will post the Full Name and Birthday to "isValiedName.php" file and that PHP file will return suggested names.

Tuesday, January 26, 2010

AJAX Using JQuery Tutorial

You may know that, JQuery is a JavaScript library that we can do smart things using small pease of code. This free and open source JavaScript Library has become the most famous JavaScript Library today because of its Lightweight, Cross-browser and CSS3 Compliant.

Using JQuery we can do thing like Document Navigating, DOM Element Selecting, Creating Animations, Event Handling and Ajax Development very easily. You can learn more about JQuery from JQuery web site.

What this post about ?

This is about a thing that we mostly want when we design web sites. I'm going to discuss how we can get that work done better and smarter using JQuery AJAX. Look at the following picture which describes the whole task, we are going to do.

Just imaging that the above picture is the structure of our web site, when we click on the links at "C", we want to load different contents to the main div in "B". If we use different web pages for all those links and load them when user clicks on a link, we are loading the content on "A" and "C" unnecessarily. That is why we should use AJAX to load the content.

First, download the following example code that I'm going to describe.

Download Source Code(Password : sara)

Open the "index.html" file in your browser and check the result by clicking links "Home", "About" and "Contact Us" on "C". Ignore the problem with last link, I'll explane that later. Now open the "index.html" using a text editor. Then you will see a code like following in the <head> </head> section.

<script src="jquery-1.3.1.min.js" type="text/javascript" ></script>

That is how you can link the JQuey to your web site, it's the same way you link a JavaScript file. Then check the following peace of code.

$(document).ready(function() { 

    //$("#main").load("home.html");
 
    $("#link1").click(function(){
        $("#main").load("home.html");
    });
 
    $("#link2").click(function(){
        $.ajax({
            url: "about.html",
            cache: true,
            beforeSend: function(){
                $("#main").slideUp("fast");
            },
            success: function(html){
                $("#main").slideDown("slow");
                $("#main").html(html);
            }
        });
    });
 
    $("#link3").click(function(){
        $.post("boo.php",  { link_id:"link3" },
        function(data){
            $("#main").html(data);
        }); 
    }); 
 
});

In JQuery we are writing events inside $(document).ready function. In the above code I have given different IDs to links and call functions when they are clicked. There I have used three different ways to get the above task done.

First look at the 5th line, there I have load the "home.html" file inside the main div when click the "Home" link (id is "link1"). That is the easiest way to do a AJAX request. Then check the 9th line. There I have load the "about.html" file inside the main div when click the "About" link (id is "link2"). This method can be used to decorate our request using effects. As above code you can use beforeSend and success functions to get that work done.

If I uncomment the 3rd line, "home.html" page will load to main div in the page load. Finally check the 23rd line, this is different than above mentioned methods. Here I have get the data in a PHP file. I have call the "boo.php" file using POST method and display the result inside main div when "Contact Us" (id is "link3") clicked. Now I think you may noticed that AJAX is simple if you use JQuery.