Monthly Archives: August 2012

Asp.Net webform popup in a new window – with a changed title text

Recently came across with a small issue which actually took lot of valuable time of my team mate as it may sound simple but was really tricky.

Issue description: You have a webform. On click of a button you need to open a popup window but title of the popup window should be changed. by default title is the url of the popup window.

Solution:

<pre><%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="PilotProject._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type ="text/javascript" >

function Test() {
        var popup = window.open('', 'name', 'height=200,width=300');
var doc = popup.document;
doc.write('<html><head><title>New popup title </title>');
doc.write('<link rel="stylesheet" href="js.css">');
doc.write('</head><body><p>New window in a popup.</p>');
doc.write('<p><a href="javascript:self.close()">close</a> the popup.</p>');
doc.write('</body></html>');
doc.close();
} </script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
      <asp:Button ID="btntest" runat ="server" OnClientClick="Test();" Text ="Test" />
</asp:Content>

Output looks like below. PLease note the different title bar text on the popup window.

Thing to notice here is that we are inserting a new html document in the popup window.and new <title> tage is also included.

Caution: If you are trying to do this in form which already has a title then it will throw an error saying that you cannot have two title
tags in a document. Though it will work it works fine if your webform has a master page with a title. Strange but it works 🙂

UPDATE: As i mentioned if you will try  to open a popup page without master page using javascript then it will throw an error for multiple <title> tags.

It happens because i was keeping the script in Head section of the parent page. If you keep the script in a .js file and include a reference in the parent page it will work fine. or just keep the script tag in <body> section.

Here is the code- without master page.

Parent.aspx:

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Parent</title>
    <script src="Scripts/Common.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnTest" Text="Test" runat="server" OnClientClick="OpenPop();" />
    </div>
    </form>
</body>
</html>

Here is the script to be included in a separate tag.

Common.js:

function OpenPop() {
    var popup = window.open('', 'name', 'width:300,height:400');
    if (popup != null) {
        var doc = popup.document;
        doc.write('<html><head> <title>I am new pop up</title></head>');
        doc.write('<body>New Window in pop up <a href="javascript:self.close();">Close this</a> </body>');
        doc.write('</html>');
        doc.close();
    }
}

The new popup window will have the new title.
Thanks Robin for your input on this!
I hope it helps!

Advertisements

Asp.Net MVC – handling multiple submit from a view

In Asp.Net MVC, after understanding of how controller communicates with Views, the biggest challenge i found was to handle multiple form submit requests. Almost every view will have multiple buttons to post/submit data (ideally a ViewModel) to controller. In this post I am assuming that you are comfortable with very basics of MVC.

To do this sample just create a Asp.Net MVC web application project and write the code in “Views/Index.cshtml” at the end because by default this is the landing page of default website template.

This code is just a sample which may not be practical in real world scenario.

@using (Html.BeginForm("MyCommonSubmitAction", "Home", FormMethod.Post)) {

<input type ="text" id="txtComments"  /> <br />

<input type="submit" name="approve" id="btnApprove" value="Approve"/>
<input type="submit" name="reject" id="btnReject" value="Reject" />
}

Now, Let us see the controller action method how it will differentiate these two submits.

[HttpPost]
public ActionResult MyCommonSubmitAction(FormCollection frm)
{
var button = frm["approve"] ?? frm["reject"];
//var comments  =  frm["txtComments"]; assuming view is not strongly typed
switch (button )
{
case "Approve" :
// do your thing
break;

case "Reject"  :
// do your thing
break;

default:
return View("Index");
}

return View("Index");

}

Now, this is just one of the ways you can differentiate multiple submit requests. Important thing to notice here is that FormCollection
is bound to the post request and is available as a parameter which actually holds all the form fields posted to the controller. Ideally every view should be bound to a strongly type ViewModel.

There are better ways of binding your data model to your view. Those who are new to Asp.Net MVC. I would recommend you to read Scott Gu post on model binding.

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