Archive

Archive for the ‘ASP.NET’ Category

Html.ActionLink VS Html Anchar Tag ()

September 18, 2013 Leave a comment

Here ,in this post i am going to describe about MVC Html.ActionLink and normal anchor tag and which one is best for use.

Html.ActionLink

Html.ActionLink use current routing configuration in Gloabl.asax.cs to prepare hyperlink at runtime. so when you modify your routing setting in said global file then Html.ActionLink directly  reference modified routing settings that you will  see below in this blog.

Anchar Tag ()

if  you use anchar tag then there is chance that your links will be broken in case routing configuration in Gloabl.asax.cs is changed. So always use Html.ActionLink over Anchar Tag that will save you time as you do not have to change all anchar tag manually  when routing configuration in Gloabl.asax.cs is changed .

Now, let’s experince this visually, Intially it is “Home/TestIndex” set as routing configuration in Gloabl.asax.cs as below and hyperlink is implemented in two way 1) Using Action Link 2) using Anchor Tag in view

Gloabl.asa


public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.MapRoute(
"CustomeTest", // Route name
"Home/TestIndex",
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
<pre>

HTML that using hyperlink in two way 1) Using Action Link 2) using Anchor Tag

<div>
<a href="../../Home/TestIndex">Back to Home (Simple Anchor Tag) </a>
<br />
<br />
@Html.ActionLink("Back to Home (Mvc Action Link)", "Index")
</div>

Now see it visually

PIC1

Here , when Back to Home (Simple Anchor Tag) link is clicked  it redirecting to home page properly .Now let’s change routing setting from “Home/TestIndex” to “Home/SuperIndex” as below then try to access same link to go to Home Page.

Pic2

so When Route settings is changed in Global.asax file then Html.ActionLink is modified accordingly but simple Anchor tag remain same so when simple Anchor tag link is clicked then you will get page not found  as below. But when link made by Html.ActionLink is clicked then it is opening concerned page properly as its Url / Hperlink is modified according to the route settings in global file

Pic3Hope you got the concept behind Html.ActionLink over Simple Anchar tag . And yes , if this post interest you then do not forget to like and comment . You can download source code from here Download Me

Thanks for your time 🙂

Single selection Checkboxlist in Asp.net with the help of JQUERY

August 2, 2012 5 comments

INTRODUCTION
As we know CheckBoxList asp.net server control that comes under “System.Web.UI.WebControls” namespace allow multi selection . In this Small post I will show you how to make single selection in CheckBoxList asp.net server control using J Query.

HTML for Control
When Binding dynamically from database

<asp:CheckBoxList ID="chkTest" runat="server"
RepeatDirection="Vertical"
RepeatColumns="1">
</asp:CheckBoxList>

When it is static

<asp:CheckBoxList ID="chkTest" runat="server"
RepeatLayout=Flow  RepeatDirection="Horizontal" Width="99%">
<asp:ListItem Text="Test1" Value="1" Selected="True"></asp:ListItem>
<asp:ListItem Text="Test2" Value="2"></asp:ListItem>
<asp:ListItem Text="Test3" Value="3"></asp:ListItem>
<asp:ListItem Text="Test4" Value="4"></asp:ListItem>
</asp:CheckBoxList>

JQuery for this

<script type="text/javascript">
$(document).ready(function() {
var checkboxes = $('#<%=chkTest.ClientID %>').find('input:checkbox');
checkboxes.click(function() {
var selectedIndex = checkboxes.index($(this));

var items = $('#<% = chkTest.ClientID %> input:checkbox');
for (i = 0; i < items.length; i++) {
if (i == selectedIndex)
items[i].checked = true;
else
items[i].checked = false;
}
});
});
</script>

I hope . you will find it helpfull.

Categories: ASP.NET, JQuery Tags: ,

The Controls collection cannot be modified because the control contains code blocks(i.e. )


Introduction:
In this post i am going to reason two things:
(1)why error “The Controls collection cannot be modified because the control    contains code blocks (i.e. <% … %>) ” come.
(2)How to solve same

Cause of error
When you add any AJAX extenders to your Web pages of your web application or try to add something in page header of web pages , it  register  scripts in the head dynamically and if any code blocks(like <% … %>) are present in the MasterPage, an error might occur.

My script in master page

<head id="head2" runat="server">
<title>Lightbox Page</title>
 <script type="text/javascript" src="<%= ResolveUrl("~/js/jquery-1.7.2.js") %>"></script>
 <script type="text/javascript" src="<%= ResolveUrl("~/js/script.js") %>"></script>
</head>

Error screen shot

Many method of solving same are:

First Method

Replace the code block with <%# instead of <%=


<script type="text/javascript" src="<%= ResolveUrl("~/js/jquery-1.7.2.js") %>"></script>
to
<script type="text/javascript" src="<%# ResolveUrl("~/js/jquery-1.7.2.js") %>"></script>

and then add this line in page load of web pages in master pages or child page( in my case it was master page.)
Page.Header.DataBind();
like

protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
}

Second Method
Remove JavaScript from the header section of web page and add it to body of the web page .
Third method
Place all your script inside <asp:placeholder runat=”server”> in header of web page
like

<head runat="server">
 <asp:ContentPlaceHolder ID="ScriptIncludePlaceHolder" runat="server">
    <script type="text/javascript" src="<%= ResolveUrl("~/js/jquery-1.7.2.js") %>"></script>
 </asp:ContentPlaceHolder>
</head>

Doing this makes code block a child of the Placeholder control, instead of being a direct child of the Page.Header control.

I hope this Will help you in solving you problem. If it help you just drop a feedback.And Any suggestion is welcomed.

Categories: ASP.NET, ASP.NET MVC, Error Tags:

Rebinding events in jQuery after Ajax update (updatepanel)


Some time we use update panel and $(document).ready(function() {});function of jquery in same page . Then whatever written inside $(document).ready(function() {});not work once we have done or performed partail post back because script inside $(document).ready(function() {}); is not bound with the page .So in this Scenario we have two option for solving the problem for the same.

  1. PageLoad event handler
  2. endRequest event of the PageRequestManager class

let see implementation of both one by one.

Using PageLoad event handler

Since we’re using ASP.NET AJAX,we’ll have access to a pageLoad event handler,that gets called each time the page posts back, be it full or partial from an UpdatePanel.You just need to put this function into your page.


function pageLoad(sender, args)
{
if (args.get_isPartialLoad())
{
//Specific code for partial postbacks can go in here.
}
}

just place your entire  $(document).ready(function() {}); inside pageLoad event handler , now our problem solved.like this.

function pageLoad(sender, args) {
$(document).ready(function() {

$("input[id$=btnMail]").click(function() {
if ($("input[id$=txtMailingList]").val() == '') {
alert('Please enter e-mail Address');
return false;
}
else if ($("input[id$=txtMailingList]").val() != '') {
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var eaddress = document.getElementById("<%=txtMailingList.ClientID %>").value;
if (reg.test(eaddress) == false) {
document.getElementById("<%=txtMailingList.ClientID %>").focus();
alert('Please enter valid email address.');
return false;
}
}
});

});
}

using endRequest event of the PageRequestManager class

endRequest event Raised after an asynchronous postback is finished and control has been returned to the browser. way of using :

Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler)
Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(endRequestHandler)

Hope this will help you in solving your problem . if it help leave a comment it encourage to write more on issue.

Categories: ASP.NET, JQuery Tags: ,

Sending email in asp.net

June 8, 2012 2 comments

Sending email’s from web applications is a very common requirement in most projects irrespective of any language site is deveoped .This article explores how to send Emails in ASP.NET  with attachments with gmail account and using custome host address.

Mail Sending using custome host address

using System.Net.Mail;
MailMessage mail = new MailMessage();
mail.To.Add("sToEmail");
mail.From = new MailAddress("sFromEmail");
if (sCCEmail.ToString() != "")
{
mail.CC.Add(sCCEmail");
}
if (sBCCEmail.ToString() != "")
{
mail.Bcc.Add("sBCCEmail");
}
mail.Subject = "put whatever subject you want to give"
mail.Body = "Your complete message you wanna share ";
mail.IsBodyHtml = true/false
SmtpClient smtp = new SmtpClient();
smtp.Host = "mail.abc.com" //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential(userName, password); //Or your Smtp Email ID and Password

smtp.EnableSsl = true/false
mail.Priority = System.Net.Mail.MailPriority.High;
mail.DeliveryNotificationOptions = System.Net.Mail.DeliveryNotificationOptions.OnFailure;

// want attachment in mail
string fileAttach = Server.MapPath("myEmails") + "\\Mypic.jpg";
Attachment attach = new Attachment(fileAttach);
mail .Attachments.Add(attach);
smtp.Send(mail);

Sending Email Using Gmail In ASP.NET.

if you don’t have a working smtp server to send mails than sending
e-mail with Gmail is best option.Otherwise use of it should be avoided
because it has some limitation like.

using System.Net.Mail;
MailMessage mail = new MailMessage();
mail.To.Add("toemailAddress");
mail.From = new MailAddress("yourid@gmail.com");
mail.Subject = "put whatever subject you want to give";
string Body = " ";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential
("YourUserName@gmail.com","YourGmailPassword");
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);

If your are getting error mentioned below “The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.”

than you need to check your Gmail username and password.

If you are behind proxy Server then you need to write below mentioned code in your web.config file

<system.net>
<defaultProxy>
<proxy proxyaddress="ProxyIpaddress"/>
</defaultProxy>
</system.net>

If you are still having problems them try changing port number to 587

smtp.Host = "smtp.gmail.com,587";

If you still having problems then try changing code as mentioned below

SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = False;
smtp.Credentials = new System.Net.NetworkCredential
("emailid@gmail.com","GmailPassword");
smtp.EnableSsl = true;
smtp.Send(mail);

If it help you solving your problem then give comment or if any wrong in this then let me know i will rectify.

Categories: ASP.NET

Keep session alive as long as you want


Most of the time we face problem of session time out . for this there are number of  options are available to solve this like:

Using Web.config file 

<system.web>
    <sessionState mode=”InProc” cookieless=”false” timeout=”15″>
    </sessionState>
</system.web>
 
 Set session timeout in Global.asax
void Session_Start(object sender, EventArgs e)
{
  // Code that runs when a new session is started
  Session.Timeout = 15;
}
 Set session timeout in IIS

Open IIS manager by typing inetmgr in Start > run in windows.
Right click on websites > Select Properties.

Go to ASP.NET tab, Click on Edit Configuration.
Click on State Management Tab, Set Session TimeOut value (In Minutes).

however all this option not work in some cases or you can say most of the time it does not works. so there is other option for same .

Using Web.config file 

<sessionState mode=”InProc” stateConnectionString=”tcpip=127.0.0.1:42424″
 sqlConnectionString=”data source=127.0.0.1;Trusted_Connection=yes” cookieless=”false” timeout=”60″/>

Using asp.net handler

step 1) Write a handler

using System;
using System.Web;
using System.Web.Services;
using System.Web.SessionState;

[WebService(Namespace = “http://tempuri.org/&#8221;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class myservice: IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
string ulname = context.Request.QueryString[“ulname”];
string ultype = context.Request.QueryString[“ultype”];
if (ultype == “a”)
{
context.Session[“UserUniqueIdAdmin”] = ulname;
}
if (ultype == “u”)
{
context.Session[“UserUniqueId”] = ulname;
}
if (ultype == “b”)
{
context.Session[“UserUniqueId”] = ulname;

}
}

public bool IsReusable
{
get
{
return false;
}
}

now you have written handler , call it from master page or any page using this java script

  <script language=”javascript” type=”text/javascript”>
        $(function() {
            setInterval(myservice123, 10000);
        });
 
        function myservice123() {
            $.post(“../myservice.ashx?ultype=a&ulname=

         ” + $(‘#<%     = dn_uid.ClientID %>’).val(), null, function() {
                alert($(‘#<%= Hdn_uid.ClientID %>’).val());
            });
        }   
    </script>

}

Hope this will solve your problem , comment is welcome for any error in this or any thing you like to share. comment encourage  to write more on issue.

 
 

Categories: ASP.NET Tags:

Request.ApplicationPath is not working


Sometime Request.ApplicationPath  does not work with all browser properly  , so use this.Request.Url.GetLeftPart(UriPartial.Authority) instead.

Lets get it by example:

If we use Request.ApplicationPath

window.open(‘” + Request.ApplicationPath + “/Massimo/ProductDetails.aspx”‘);
It will be rendered as http://Massimo/ProductDetails.aspx that i do not want

If we use Request.Url.GetLeftPart(UriPartial.Authority)

then it will be rendered as  http://ServerName/Massimo/ProductDetails.aspx that is what we want.

I hope it will be helpful in your problem , if it help you ,give give Comment that make me post more solution of day to day problem occurred in our programming life.

Categories: ASP.NET Tags:
%d bloggers like this: