Monday, August 24, 2015

Warn User if Back is Pressed

You may want to warn user if Back button is pressed. This works in most of the cases. If you have some unsaved form data, you might want to trigger a warning message to user if Back button is pressed.
Following Javascript snippet will add a warning message in case Back button is pressed:

window.onbeforeunload = function() { return "You work will be lost."; };


for detail click here

Disable Back Button in Browser using JavaScript

We can disable the back navigation by adding following code in the webpage. Now the catch here is that you have to add this code in all the pages where you want to avoid user to get back from previous page. For example user follows the navigation page1 -> page2. And you want to stop user from page2 to go back to page1. In this case all following
<SCRIPT type="text/javascript">
    window.history.forward();
    function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();"
    onpageshow="if (event.persisted) noBack();" onunload="">


The above code will trigger history.forward event for page1. Thus if user presses Back button on page2, he will be sent to page1. But the history.forward code on page1 pushes the user back to page2. Thus user will not be able to go back from page1.

Thursday, August 13, 2015

Show Last Visited Pages from Cookie using Javascript & JQuery Or Store User Latest Visit Pages in Cookie

You need to just add this js code on you page and provide the class id where you wanted to show your result only, rest of the thing my code will do

/************By Murli on 12 Aug 2015 ********************/
/*******Purpose: To show last 4 visited pages using object & array on the site***************/
/********* http://murlid05.blogspot.in/ *****************/

var template = { Title: "", Desc: "Temp Name", Url: "" };

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString() + "; path=/";
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

function checkCookie(PageTitle, PageDescription, PageUrl) {

    var newArray = new Array(); /*Temp Array to generate cookie*/
    var tempObject = ""; /*To hold the already exists page data*/
    var arrObject;  /*To store cookie value in a object*/

    if (getCookie("RecentViewList") != '') {
        arrObject = $.parseJSON(getCookie("RecentViewList")); /* Convert string to object */
    }

    if (arrObject != null) {
        $.each(arrObject, function (index, value) {
            if (PageUrl == value.Url) {
                tempObject = { Title: PageTitle, Desc: PageDescription, Url: PageUrl };
            } else {
                newArray.push({ Title: value.Title.toString(), Desc: value.Desc.toString(), Url: value.Url.toString() });
            }
        });
    }

    if (tempObject != "") {
        newArray.push(tempObject);
    } else {
        if (newArray.length > 3) newArray.splice(0, 1); /*Remove most recent value from array*/
        tempObject = { Title: PageTitle, Desc: PageDescription, Url: PageUrl };
        newArray.push(tempObject);
    }

    var stringObj = JSON.stringify(newArray); /*Convert Array to JSON formated string*/
    setCookie("RecentViewList", stringObj, 1);

    FnShowonPage(); /*Draw on a page*/
}


function FnShowonPage() {
    var arr = getCookie("RecentViewList");
    var Description = "";
    arr = $.parseJSON(arr);
    var HtmlData = "<a class='closerightFloater' href='javascript:;'></a><ul class='browserVisitlist'>";
    $.each(arr, function (index, value) {
        Description = (value.Desc.length > 120) ? (value.Desc.substring(0, 120) + "....") : value.Desc;
        HtmlData += "<li><a class='recentLinks' title=" + value.Title + "' href='" + value.Url + "' >" + value.Title.substring(0, 25) + "</a><p>" + Description + "</p></li>";
    });
    HtmlData += "</ul>";
    $(".rightPanelbrowsebig").html(HtmlData);
}


$(document).ready(function () {
    var PageDescription = $("meta[name='description']").attr("content");
    var PageTitle = document.title.replace("é","e");
    var PageUrl = window.location.href;

    if ((typeof document.title !== "undefined") && (typeof $("meta[name='description']").attr("content") !== "undefined")) {
        PageDescription = (typeof $("meta[name='description']").attr("content") !== "undefined") ? PageDescription : "No";
        // alert(PageDescription + "  ::Under On load:   " + PageTitle + "  ::::     " + PageUrl);
        checkCookie(PageTitle.toString(), PageDescription.toString(), PageUrl.toString());
    }
    else {
        //alert("somthing wrong   :   " + PageTitle);
    }
})

Wednesday, July 8, 2015

Download excel report in MVC


public ActionResult Download(string working)
        {
           // return View();
            ViewBag.Message = "Welcome to Report Generation!";
            Temp cm = new Temp();
            List model = cm.getAll();
            GridView gv = new GridView();
            gv.DataSource = model;
            gv.DataBind();
            Session["temp"] = gv;


            if (Session["temp"] != null)
            {
                return new DownloadFileActionResult((GridView)Session["temp"], "temp.xls");
            }
            else
            {
                //Some kind of a result that will indicate that the view has 
                //not been created yet. I would use a Javascript message to do so. 
                return View(model);
            }
            //return View(model);
        }
 public class Temp
    {
        public int id { get; set; }
        public string Name { get; set; }
        public Temp() { }
        Temp(int _id,string _name)
        {
            id = _id;
            Name = _name;
        }
        public List getAll()
        {           
            List list = new List();
            list.Add(new Temp(1, "Murli"));
            list.Add(new Temp(3, "Deepak"));
            list.Add(new Temp(5, "Prakash"));
            list.Add(new Temp(7, "Mahandar"));
            return list;
        }
    }

public class DownloadFileActionResult : ActionResult
{
    public GridView ExcelGridView { get; set; }
    public string fileName { get; set; }
    public DownloadFileActionResult(GridView gv, string pFileName)
    {
        ExcelGridView = gv;
        fileName = pFileName;
    }

    public override void ExecuteResult(ControllerContext context)
    {

        //Create a response stream to create and write the Excel file
        HttpContext curContext = HttpContext.Current;
        curContext.Response.Clear();
        curContext.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
        curContext.Response.Charset = "";
        curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        curContext.Response.ContentType = "application/vnd.ms-excel";

        //Convert the rendering of the gridview to a string representation 
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        ExcelGridView.RenderControl(htw);

        //Open a memory stream that you can use to write back to the response
        byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
        MemoryStream s = new MemoryStream(byteArray);
        StreamReader sr = new StreamReader(s, Encoding.ASCII);

        //Write the stream back to the response
        curContext.Response.Write(sr.ReadToEnd());
        curContext.Response.End();
    }
}  

Use multiple submit button on MVC


Create two submit button inside the form
<form action="index"> <input type="submit" name="submitButton" value="Filter" /> <input type="submit" name="submitButton" value="Download" /> </form>
on the controller action use switch case to target the final action command
public ActionResult Index(StatisticsReport stc, string submitButton) { switch (submitButton) { case "Filter" : break; case "Download": return RedirectToAction("Download", list); } } public ActionResult Download(List list) { return View(); }

Tuesday, November 18, 2014

Thursday, September 11, 2014

How to use JQuery Selectors?

The selectors are very useful and would be required at every step while using jQuery. They get the exact element that you want from your HTML document.
Following table lists down few basic selectors and explains them with examples.
SelectorDescription
NameSelects all elements which match with the given element Name.
#IDSelects a single element which matches with the given ID
.ClassSelects all elements which match with the given Class.
Universal (*)Selects all elements available in a DOM.
Multiple Elements E, F, GSelects the combined results of all the specified selectors E, F or G.
Similar to above syntax and examples, following examples would give you understanding on using different type of other useful selectors:
  • $('*'): This selector selects all elements in the document.
  • $("p > *"): This selector selects all elements that are children of a paragraph element.
  • $("#specialID"): This selector function gets the element with id="specialID".
  • $(".specialClass"): This selector gets all the elements that have the class of specialClass.
  • $("li:not(.myclass)"): Selects all elements matched by
  • that do not have class="myclass".
  • $("a#specialID.specialClass"): This selector matches links with an id of specialID and a class of specialClass.
  • $("p a.specialClass"): This selector matches links with a class of specialClass declared within elements.
  • $("ul li:first"): This selector gets only the first
  • element of the
      .
  • $("#container p"): Selects all elements matched by that are descendants of an element that has an id of container.
  • $("li > ul"): Selects all elements matched by
      that are children of an element matched by
  • $("strong + em"): Selects all elements matched by that immediately follow a sibling element matched by .
  • $("p ~ ul"): Selects all elements matched by
      that follow a sibling element matched by .
  • $("code, em, strong"): Selects all elements matched by or or .
  • $("p strong, .myclass"): Selects all elements matched by that are descendants of an element matched by as well as all elements that have a class of myclass.
  • $(":empty"): Selects all elements that have no children.
  • $("p:empty"): Selects all elements matched by that have no children.
  • $("div[p]"): Selects all elements matched by
    that contain an element matched by .
  • $("p[.myclass]"): Selects all elements matched by that contain an element with a class of myclass.
  • $("a[@rel]"): Selects all elements matched by that have a rel attribute.
  • $("input[@name=myname]"): Selects all elements matched by that have a name value exactly equal to myname.
  • $("input[@name^=myname]"): Selects all elements matched by that have a name value beginning with myname.
  • $("a[@rel$=self]"): Selects all elements matched by that have rel attribute value ending with self
  • $("a[@href*=domain.com]"): Selects all elements matched by that have an href value containing domain.com.
  • $("li:even"): Selects all elements matched by
  • that have an even index value.
  • $("tr:odd"): Selects all elements matched by that have an odd index value.
  • $("li:first"): Selects the first
  • element.
  • $("li:last"): Selects the last
  • element.
  • $("li:visible"): Selects all elements matched by
  • that are visible.
  • $("li:hidden"): Selects all elements matched by
  • that are hidden.
  • $(":radio"): Selects all radio buttons in the form.
  • $(":checked"): Selects all checked boxex in the form.
  • $(":input"): Selects only form elements (input, select, textarea, button).
  • $(":text"): Selects only text elements (input[type=text]).
  • $("li:eq(2)"): Selects the third
  • element
  • $("li:eq(4)"): Selects the fifth
  • element
  • $("li:lt(2)"): Selects all elements matched by
  • element before the third one; in other words, the first two
  • elements.
  • $("p:lt(3)"): selects all elements matched by elements before the fourth one; in other words the first three elements.
  • $("li:gt(1)"): Selects all elements matched by
  • after the second one.
  • $("p:gt(2)"): Selects all elements matched by after the third one.
  • $("div/p"): Selects all elements matched by that are children of an element matched by
    .
  • $("div//code"): Selects all elements matched by that are descendants of an element matched by
    .
  • $("//p//a"): Selects all elements matched by that are descendants of an element matched by
  • $("li:first-child"): Selects all elements matched by
  • that are the first child of their parent.
  • $("li:last-child"): Selects all elements matched by
  • that are the last child of their parent.
  • $(":parent"): Selects all elements that are the parent of another element, including text.
  • $("li:contains(second)"): Selects all elements matched by
  • that contain the text second.
You can use all the above selectors with any HTML/XML element in generic way. For example if selector $("li:first") works for
  • element then $("p:first") would also work for element.