Category Archives: Jquery

How to open partial view as modal dialog in asp.net mvc

Asp.Net MVC is picking up fast and yet there is not much expertise around it. Main reason I feel is now developer has complete control on markup so they approach in different ways. It is difficult to for a beginner to implement any design principles.

Anyway, today I am going to showcase how to open a partial view dynamically as a popup using Jquery. I am hoping you have basic idea of how MVC works and you know the Jquery syntax.

View code: Main page ProductView.cshtml. click on the image to see the .cshtml code.
wordpress

Partial view html for list.
code2

Old classic view of productList page (it is also a partial view which rendres as a grid) with edit/delete links in each row. When you click on edit link in the grid, updateDialog div will open as a modal popup and load a partial view in that div dynamically using below code.

Controller action method which returns the partial view to be loaded in div updateDialog.

public ActionResult EditPartialGet(int id)
{
ProductViewModel productVM = new ProductViewModel();
Product p = new Product();
p = productVM.GetById(id);
return PartialView("ProductUpdatePartial",p);
}

finally jquery code to open popup and load partial view using ajax call.

$(function () {
// on click of editLink in grid.
$(“#editLink”).live(‘click’, function () {

var hrefValue = $(this).attr(“href”);
var index = hrefValue.lastIndexOf(“/”) + 1;
var productId = hrefValue.substring(index, hrefValue.length);
// this will call EditPartialGet action method in Products controller which returns
// a partial view html.
$.ajax({
type: “GET”,
url: “Products/EditPartialGet?id=” + productId,
datatype: “json”,
contentType: “application/json”,
success: function (data) {
$(“#updateDialog”).html(data);// returned data is an html view which will be rendered inside the div.
return false;
},
error: function (a, b, c) { alert(b); }
});

$(“#updateDialog”).dialog(
{
modal: true,
buttons: {
// in modal dialog popup Save button will be created. write what you want to do here.
Save: function () {

var ctx = $(“#updateDialog”);
debugger;
// parse the DOM within context of div id.
var product = {
ProductID : $(“#ProductID”,ctx).val(),
ProductName : $(“#ProductName”,ctx).val(),
SupplierID : $(“#SupplierID”, ctx).val(),
CategoryID : $(“#CategoryID”, ctx).val(),
QuantityPerUnit: $(“#QuantityPerUnit”, ctx).val(),
UnitPrice : $(“#UnitPrice”, ctx).val(),
UnitsInStock : $(“#UnitsInStock”, ctx).val(),
UnitsOnOrder : $(“#UnitsOnOrder”, ctx).val(),
ReorderLevel : $(“#ReorderLevel”, ctx).val(),
Discontinued : $(“#Discontinued”, ctx).attr(“checked”)
};

$.ajax({
type: “POST”,
url: “Products/Update”,
data: JSON.stringify(product),
datatype: “json”,
contentType: “application/json”,
success: function (data) {
// submit the data
alert(‘done’);
return false;
},
error: function (a, b, c) { debugger; alert(b); }
});

$(“#updateDialog”).dialog(‘close’);
return false;
},
Cancel: function () { $(“#updateDialog”).dialog(‘close’); }
}
});
return false;
});
});

I think the above code is all you need to implement dynamically loading of partial view in a div.

I hope it helps.

Moving Items from one ListBox to another ListBox using Jquery

Jquery can do this real quick and with good user experience. You might need to style it up a bit.

UI code:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="Test" %>

 <!DOCTYPE html>

 <html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
  <title></title>
  <script src="Scripts/jquery-1.7.1.js"></script>

 <script>

 $(document).ready(function () {

 var productLineId = $("#ddlProductLine").val();
  var lBox = $('select[id$=lbCountriesAll]');
  var lBox2 = $('select[id$=lbSelectedCountries]');

 $("#btnSelect").click(function (e) {

 var selectedValues = $('#lbCountriesAll option:selected');
  if(selectedValues.length == 0)
  {
  alert('Please select a country.');
  e.preventDefault();
  }

 if (selectedValues.length > 3) {
  alert('You cannot select more than 3 countries.');
  e.preventDefault();
  }
  else {
  //debugger;
  var children = $('#lbSelectedCountries').children();
  if (children.length >= 3) {
  alert('You cannot select more than 3 countries.');
  e.preventDefault();
  }
  else {
  $('#lbSelectedCountries').append($(selectedValues).clone());
  $(selectedValues).remove();
  e.preventDefault();
  }

 }
  })

 $("#btnUnSelect").click(function (e) {
  //debugger;

 var selectedValues = $('#lbSelectedCountries option:selected');
  if (selectedValues.length == 0) {
  alert('Please select a country.');
  e.preventDefault();
  }

 $('#lbCountriesAll').append($(selectedValues).clone());
  $(selectedValues).remove();
  e.preventDefault();

 })

  });
  </script>

 </head>

 <body>
  <form id="form1" runat="server">
  <div>

 <table>

 <tr><td>

 <asp:ListBox ID="lbCountriesAll" runat="server" Width="200px" Height="350px" SelectionMode="Multiple" ></asp:ListBox></td>

  <td>
  <asp:Button ID="btnSelect" runat="server" Text=">>"></asp:Button><br />
  <asp:Button ID="btnUnSelect" runat="server" Text="<<"></asp:Button>
  </td>
  <td>
  <asp:ListBox ID="lbSelectedCountries" runat="server" Width="200px" Height="350px" SelectionMode="Multiple"></asp:ListBox></td>
  </tr>

 </table>

 </div>
  </form>
 </body>
 </html>

The above code will transfer the items from one Listbox to another and can also limit the number of items a user can transfer. You can remove that code if you do not need it.

Code Behind:The code below only binds the Listbox with some countries.


protected void Page_Load(object sender, EventArgs e)
 {
 if (!IsPostBack)
 {
 lbCountriesAll.DataSource = GetCountries();
 lbCountriesAll.DataTextField = "Name";
 lbCountriesAll.DataValueField = "ID";
 lbCountriesAll.DataBind();
 }

}

&nbsp;

public static List<Country> GetCountries()
 {
 List<Country> Countries = new List<Country>()
 {
 new Country() { ID=4, Name="Afghanistan"},
 new Country() { ID=918, Name="Åland Islands"},
 new Country() { ID=8, Name="Albania"},
 new Country() { ID=12, Name="Algeria"},
 new Country() { ID=16, Name="American Samoa"},
 new Country() { ID=20, Name="Andorra"},
 new Country() { ID=24, Name="Angola"},
 new Country() { ID=660, Name="Anguilla"},
 new Country() { ID=10, Name="Antarctica"},
 new Country() { ID=28, Name="Antigua and Barbuda"},
 new Country() { ID=32, Name="Argentina"},
 new Country() { ID=51, Name="Armenia"},
 new Country() { ID=533, Name="Aruba"},
 new Country() { ID=36, Name="Australia"},
 new Country() { ID=40, Name="Austria"},
 new Country() { ID=31, Name="Azerbaijan"},
 new Country() { ID=44, Name="Bahamas, The"},
 new Country() { ID=48, Name="Bahrain"},
 new Country() { ID=50, Name="Bangladesh"},
 new Country() { ID=52, Name="Barbados"},
 new Country() { ID=112, Name="Belarus"},
 new Country() { ID=56, Name="Belgium"},
 new Country() { ID=84, Name="Belize"},
 new Country() { ID=204, Name="Benin"},
 new Country() { ID=60, Name="Bermuda"},
 new Country() { ID=64, Name="Bhutan"},
 new Country() { ID=68, Name="Bolivia"},
 new Country() { ID=912, Name="Bonaire, Sint Eustatius and Saba"},
 new Country() { ID=70, Name="Bosnia and Herzegovina"},
 new Country() { ID=72, Name="Botswana"},
 new Country() { ID=74, Name="Bouvet Island"},
 new Country() { ID=76, Name="Brazil"},
 new Country() { ID=86, Name="British Indian Ocean Territory"},
 new Country() { ID=96, Name="Brunei"},
 new Country() { ID=100, Name="Bulgaria"},
 new Country() { ID=854, Name="Burkina Faso"},
 new Country() { ID=108, Name="Burundi"}

};

return Countries;

}

I am using a web application to demonstrate here. You can use the same code in MVC too, only thing you need to change is the URL you are pointing to in $.ajax call. It would point to an action method from a controller class.
Similarly, you can use the same code with HTML 5 app, only the Url will point to some Http service.

I hope it helps!

 

Jquery – Cross domain script call – No transport error

I have spent few hours figuring out that why my below code is not working. This piece of code is beeing called from a asp.net website. It is calling a WebApi http service using jquery ajax api.

$(document).ready(function () {
$.ajax({
    url: "http://localhost:65209/api/values/SayHello",
    type: "GET",
    success: function (result) { alert(result);  },
    error:   function () { alert('error'); }
});

The reason was that using ajax I was trying to make a cross domain script call whiich by default will throw an error saying “No Transport”.
the solution is to introduce one line which was introduced after jquery 1.4.1 version onwards. Just add this line after $(document).ready() itself.

jQuery.support.cors = true;

That’s it! the same code works fine for me.

Note: Even though it works fine for you if you create your own service layer and website is trying to consume it. But there are few public websites  like netflix which does not allow cross domain scripting.

I hope it helps!

Json data – Thinner and familiar data format

I have written a little about json in bits and pieces in my erlier posts but moving further i felt a strong urge to put it altogether about Json. Mainly from development perspective which should cover from basic syntax to serialization and desrialization of json data. It also consists of links to good articels wherever needed.

Json (Javascript object notation) is a data format which is a thinner and cleaner than xml/soap formats. I am putting main points here that can get you started right away. Please refer to W3Schools on Json for the detailed syntax.

  • Data is in name/value pairs
  • Data is separated by comma
  • Json values can be integer,floating point,string(in double quotes),boolean (true/false),Array (square brackets), object(curly brackets) or NULL

Mostly we deal with object oriented way of representation so let me take an example.

Employee.cs it is a c# class.


public class Employee{

public string Name {get;set;}

public int      Age    {get;set;}

public bool   IsPermanent {get; set;}

Json representation of an Employee object:


// single object of an employee

{"Name" : "praveen" , "Age" : 30, "IsPermanent" : true }

// list or array of employees. please note the square brackets.

var employeesArray = [

{ "Name" : "praveen"   , "Age" : 30 ,"IsPermanent" : true} ,

{ "Name" : "amit"      , "Age" : 27 ,"IsPermanent" : false} ,

{ "Name" : "sudhakar"  , "Age" : 27 ,"IsPermanent" : true}

]

Now that you must be comfortable with the syntax of Json data. next step is to understand how to handle Json data effectively.In this post i will discuss how to consume a webapi http service which returns an object in Json data format.

Note: To create WebApi service please refer to My Post on How to create a WebApi

Let us see few jquery methods we can use to fetch Json data.

Using $.ajax(type,uri,onSuccessMethod,onErrorMethod): .ajax() is much familiar method as it is more generic in nature and can call “Get”, “Post” etc. type of requests. you can also specify content type (default is xml).


function find() {
var id = $('#empId').val();
var httpApiUri = "api/employees/" + id;
$.ajax (
type   :  "GET",
url     :   httpApiUri ,
contentType : "json",

success  : function(data){
              $.each(data, function (index,item){
               $("#employeestable").append("<tr><td>" + item.FirstName + "</td>" + "<td>" + item.LastName + "</td>");
              });
           },
error   :  function (jqXHR, textStatus, err) {
             alert('Error: ' + err);
           });
);
}

Using $.getJSON(uri,successmethod): Unlike $.ajax() method this one is specific to “Get” type of requests and fetch the data in Json format by default which is great if you are sure of your data format beforehand.

function find() {
var id = $('#empId').val();
var httpApiUri = "api/employees/" + id;
$.getJSON ( httpApiUri , function(data){
                         $.each(data, function (index,item){
                               $("#employeestable").append("<tr><td>" + item.FirstName + "</td>" + "<td>" + item.LastName + "</td>");
                               });
                         }
          )
          .fail( function (jqXHR, textStatus, err) {
              alert('Error: ' + err);
           });
}

How to send the json data as a parameter?
Now that you know how to represent Json data using javascript notation and jquery syntax.Next step is to serialize your normal data say a javascript variable and send it as a parameter to a webapi service for instance. I am considering Jquery as an example here as it is the most widely acceptable cross browser javascript library. There are various jquery apis available to achieve this.

Using JSON.stringify( jsonData ):  Let’s say i want to make a “post” request to add an employee using an http service. you can use JSON.stringify() method which is available on Json2.js on GitHub.You need to include this js file in your code. This method will serialize your javascript variable into json format and send it over the wire.

Note: One important thing about $.ajax() method is that the parameters contentType  is a format which is returned on success of the call. data  is the parameter which defines datatype of the parameter you are sending to the service. both in this example are json.


<script type="text/javascript">

$("#btnInsert").click( function() {

var empObj ='{ "FirstName" : "Praveen"   , "LastName" : "Saxena"}' ;

$.ajax({

type: 'POST',
url: 'http://serverName:portNo/Employees/PostEmployee',
data: <strong>JSON.stringify(empObj </strong><strong>)</strong>,
contentType: 'application/json',
processData: true,
success: function (result) {
$('#results').html('Result: ' + JSON.stringify(result));
},
error: function (xhr, status, error) {
$('#results').html('Error: ' + xhr.responseText);
}
});

}
</script>


Using jQuery.ParseJSON(jsonData):
This method is added in jquery version -1.4.1 onwards so you dont need to include any other js file. It performs the similar operation.


<script type="text/javascript">

$("#btnInsert").click( function() {

var empObj ='{ "FirstName" : "Praveen"   , "LastName" : "Saxena"}' ;

$.ajax({

type: 'POST',
url: 'http://serverName:portNo/Employees/PostEmployee',
data: <strong>jQuery.parseJSON(empObj </strong><strong>)</strong>,
contentType: 'application/json',
processData: true,
success: function (result) {
$('#results').html('Result: ' + JSON.stringify(result));
},
error: function (xhr, status, error) {
$('#results').html('Error: ' + xhr.responseText);
}
});

}
</script>

Deserializing JSON data: Now that you know 1) Json syntax 2) jquery apis to send json data as parameter, we need to know how to deserialize the json data at code side. We have several ways to do it.
I found Json.net library very easy to use and i have a detailed post dedicated to JSON.Net. Please refer to  My Post on Json.Net to serialize an deserialize Json data

Now if you are given your next task on jquery with services dealing with json data, i guess you are good to go 🙂 (or at least googled code will start making sense if you are not fully prepared)

Hope it helps!

Praveen

 

Jquery to scroll down or up OnClick of an anchor tag

Recently i was working on an MVC master detail grid UI. There is a master grid which shows link to detail grid. When you click on the link of any row, a detail grid appears below the master grid. So the issue was detail grid did not have focus onclick of master link. which was very much desired by the user.

Here is a the small piece of jquery code which solved the problem. It not only scrolls down but also provides a decent animation effect while sliding down/up.


$(function () {
$(".productsLink").live('click', function () {
$('html,body').animate({scrollTop: $("#products").offset().top }, "slow");
});
});

Where products is the id of detail div.

Hope it helps!
Praveen