Thursday, September 27, 2012

Show Successfull Message Using Jquery in asp.net



.aspx
<script type="text/javascript">
function ShowErrorMessage() {
$(document).ready(function () {
$(".ErrorMsgContainer").stop(true, true).show("slide", { direction: "up", opacity: 0.4 }, 0);
setTimeout(function () {
$(".ErrorMsgContainer").stop(true, true).hide("slide", { direction: "up", opacity: 0.4 }, 500);
  }, 10000);
 });
}
function HideErrorMessage() {
   $(document).ready(function () {
  $(".ErrorMsgContainer").stop(true, true).hide();
 });
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequest);
  function EndRequest(sender, args) {
    HideErrorMessage();
    ShowErrorMessage();                
  }
</script>
<style>
.ErrorMsgContainer
{
 position: fixed;             
 display: none;
 background-color: Yellow;
 border: 1px solid;
 padding: 5px;
 padding-left: 30px;
 padding-right: 30px;
 color: #fff;
 font-size: 12px;
}
</style>
<div class="ErrorMsgContainer">
    <asp:Literal ID="ltrErrorMsg" runat="server"></asp:Literal>
</div>
.aspx.CS
HideErrorMessage(ltrErrorMsg, string.Empty);
ShowErrorMessage(ltrErrorMsg, "Data Saved Successfully");

Data Formatting for DataTextFormatString field for dropdownlist in asp.net



int ID = convert.ToInt32(ddl.SelectedItem.Value)
tblEntities Entities = new tblEntities();
ddl.DataSource = Entities.widget.Where(p => p.MID == ID).ToList();
ddl.DataTextField = "ID";
ddl.DataValueField = "ID";        
ddl.DataTextFormatString = "Widget - " + "{0}"; <------ Formatted Text
ddl.DataBind();
ddl.Items.Insert(0, new ListItem("--Select--", "-1"));

Using Joins Linq in asp.net

 var query = Entities.admin      
                    .Join(Entities.adminpermissions,       
                    c => c.ID,        
                    cm => cm.PID,  
                    (c, cm) => new { PRead = cm.PRead, UserId = cm.UserID, ID = cm.ID }) // project result
                    .Where(x => x.UserId == userID);  // select result

FindControl of masterpage from childpage in asp.net


LinkButton lbtn3rdItem = (LinkButton)Page.Master.
FindControl("lbtn3rdItem");
lbtn3rdItem.Text = "Configurations";

 

A potentially dangerous Request.Form value - Error


If  we try to insert some html formatted data in
database using richtextbox / textbox(multiline) we will get error like "A potentially dangerous
Request.Form value was detected from the client in ASP.NET WebForms"....


Then we can follow like below .aspx
ValidateRequest="false"  //in page directive(<%@ Page %>) (or)

Web.Config
<httpRuntime requestValidationMode="2.0"/>  //web.config
But if there is no httpRuntime section in the web.config file, then it should inside the <system.web> section.




Wednesday, September 26, 2012

How to make a CheckBoxList Items as a HyperLink

.aspx code


 <script type="text/javascript">
function test() {
            
 }
        
</script>

<asp:CheckBoxList ID="chkEvents" runat="server" RepeatLayout="Table" RepeatColumns="3" CellPadding="10" CellSpacing="10" RepeatDirection="Horizontal">
<asp:ListItem Text=" Join Us " Value="0">
                    </asp:ListItem>
<asp:ListItem Text=" Earnings " Value="1">                     </asp:ListItem>
 <asp:ListItem Text=" Redemption " Value="2"></asp:ListItem>
</asp:CheckBoxList>

.aspx.cs code

foreach (ListItem chk in chkEvents.Items)
 {
   if (chk.Selected)
   {

     chk.Text = " <a href='javascript:test();'>" + chk.Text +   "</a>";
   }

}

//using javascript method in href   --- chk.Text = " <a href='javascript:test();'>" + chk.Text + "</a>";
and also we can call script from anchor tag in the above example.

Displaying text with in the span using jquery


<script type="text/javascript">
function test()
{
 $('#spanHead').html(text);
}
</script>

Display block / none using jquery


<script type="text/javascript">
        function OpenPanel() {
            $("#<%= pnlTemplate.ClientID%>").css("display", "block");
            $("#<%= pnlEvents.ClientID%>").css("display", "none");
        }

    </script>
In the above Javascript i hide one panel and showing another panel using jquery display block and display none with css

Tuesday, September 18, 2012

Insert and Select statements Using Linq in asp.net

Custom Search

tblcandidateData cdata = new tblcandidateData();

tcdata.FirstName = txtfirstname.Text;
tcdata.LastName = txtlastname.Text;
tcdata.EMail = txtfstemail.Text;
tcdata.CellPhone = txtcellphone.Text;
tcdata.Address = txtaddress.Text;
tcdata.City = txtcity.Text;
tcdata.CreatedOn = System.DateTime.Now.Date;
tcdata.Rate = Convert.ToDecimal(txtrate.Text);
dc.tblcandidateDatas.InsertOnSubmit(tcdata);
dc.SubmitChanges();



Select Statement Using Linq in asp.net


int pid=Convert.ToInt32(Session["PartnerId"]); 
var candidates = from p in dc.tblcandidatedatas where p.PartnerId == pid select p;
grvCandidates.DataSource = candidates;
grvCandidates.DataBind();

 

Get Extension of Uploaded file in asp.net

Custom Search

string strFileName = Path.GetFileName(fUpload1.PostedFile.FileName);
//above line we will get the uploaded filename
string strExtn = Path.GetExtension(fUpload1.PostedFile.FileName);
//above line we will get the extension of uploaded file

Sunday, September 16, 2012

FocusOut Event Using jquery in asp.net

Custom Search


$(document).ready(function() {
$('#dobText').focusout(function () {
                $("#dobText").hide();
                $("[id*=spanDOB]").show();
 });

});


Click Event Using Jquery in asp.net


$(document).ready(function() {
 $('[id*=spanDOB]').click(
function () {
                $("#dobText").show();
                $("[id*=spanDOB]").hide();
            });
});
 

MouseOut Event Using Jquery in asp.net


$(document).ready(function() {
$('[id*=spanDOB]').mouseout(
function () {
                $("[id*=spanDOB]").css("border", "0px");
            });
});

MouseOver Using Jquery in asp.net


$(document).ready(function() {
  $('[id*=spanDOB]').mouseover(function () {
                $("[id*=spanDOB]").css("border", "10px solid #F0F0F0");
            });
});

Friday, September 14, 2012

Decimal Precision Using Regex in asp.net

public static string AdjustDecimalPrecision(decimal value)
{
            return new Regex("\\d+(\\.\\d{1,2})?"). Match(value.ToString()).ToString();  
   
}

Namespace for Regex
using System.Text.RegularExpressions;

Call ASP.NET server side method using jQuery in asp.net

 function UpdateProfile() {

            $.ajax({
                cache: false,
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "webservice.asmx/UpdateProfile",
                data: "{'strAbout':'" + $('#<%=txtAbout.ClientID%>').val()
                    + "','strAddress':'" + $('#<%=txtAddress.ClientID%>').val()
                    + "','strGender':'" + $('#<%=txtGender.ClientID%>').val()
                    + "'}",
                dataType: "json",

                success: function (data) {
                    var coupons = data.d;
                },
                failure: function (msg) {
                    alert(msg);
                }

            });
        }
above code is for jquery call server side method in asp.net or Calling ASP.NET server side method using jQuer.

webservice.asmx.Cs :

 [WebMethod]
    public string UpdateProfile(string strAbout, string strAddress, string strGender)
    {
        userDTO objUserDto = new userDTO();
        objUserDto.ID = Convert.ToInt64(UserID);
        objUserDto.About = strAbout;     
        objUserDto.Gender = strGender;
        objUserDto.Address = strAddress;
        UserService UService = new UserService(new UserRepository());
        UService.UpdateUserProfileLB(objUserDto);
        return "Updated Successfully";
    }

Friday, September 7, 2012

ReplaceWith X of except last 4 digits of account number in asp.net


public string ReplaceWithX(string ReplaceFor)
    {
        string strReplace = string.Empty;
        string strlastdigits = string.Empty;
        int LastDigits = ReplaceFor.Length - 4;
        strReplace = ReplaceFor.Substring(0, ReplaceFor.Length - 4);
        
        for (int i = 0; i < strReplace.Length; i++)
        {
            strlastdigits += strReplace[i].ToString().Replace(strReplace[i].ToString(), "x").ToString();
        }
        strlastdigits += ReplaceFor.Substring(LastDigits);
        return strlastdigits;
    }

This method is useful for ReplaceWithX of account number except last 4 digits...

Dynamic ToolTip For linkbutton in asp.net



.aspx.cs

 lbtnTxn.Attributes.Add("onmouseover", "showTooltip(" + strJSValues.ToString() + ");"); lbtnTxn.Attributes.Add("onmouseout", "HideTooltip();"); 

.aspx

<script type="text/javascript" language="javascript">
function showTooltip(name, AccNo, Product) 
{
 document.getElementById("tdName").innerText = "Name : " + name; document.getElementById("tdAcNum").innerText = "Account No : " + AccNo; 
x = event.clientX + document.body.scrollLeft-10; 
y = event.clientY + document.body.scrollTop + 20;
  pop.style.display = "block";
  pop.style.left = x - 10;
  pop.style.top = y - 50;
 }
 function HideTooltip() 
{
  pop.style.display = "none";
 }

</script>

<div id="pop"> <table border="1" cellpadding="1" cellspacing="1" style="width: 98%px;">
<tbody>
<tr>
<td id="tdName"></td>
</tr>
<tr>
<td align="left" class="runtext" id="tdAcNum"></td>
</tr>
</table>
</div>
This code can help for Dynamic ToolTip For linkbutton in asp.net

Disable Cut,Copy and Paste for textbox Using Jquery In asp.net

$(document).ready(function () { 
$('#<% = txtFromDate.ClientID %>').bind('copy paste cut', function (e) 
{ e.preventDefault();  
}); });

This Code can disable cut text from textbox,copy the text from textbox and paste in textbox

Validation Expression for pincode in asp.net

validation expression for pincode checking \d{0,6} 

^\w+$ - text without spaces and numbers

http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)? -
for url

^[0-9]+$ - for numbers

\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*    -  for email
 
 

Confirmation Message While deleting a record from gridview in asp.net

<script type="text/javascript">

function confirmationBox() {
            var r = confirm("Are you sure you want to delete? Click Ok to continue");
            if (r) {
                return true;
            }
            else {
                return false;
            }
        }

</script>


<asp:LinkButton ID="lbtnDelete" runat="server" Text="Delete"
                                        CommandArgument='<%# Eval("ID") %>' CommandName="Delete" OnClientClick="return confirmationBox();"></asp:LinkButton>


// this is for Confirmation Message While deleting a record from gridview or listview, if you say confirm it will delete the record,otherwise if we select cancel it shouldn't delete a record in asp.net

Search

Custom Search
Protected by Copyscape Plagiarism Software