How To Show Confirm Alert Box In ASP.NET MVC Before Deleting Record

In this article, we will learn how to show the confirm alert box before deleting or ensuring any user action. Let's consider we have the following html table which has a list of records.
<table class="table">
 <tr>
 <th>
 @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.City)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Address)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)

    {
        @Html.HiddenFor(model => item.Empid)
        <tr>
           <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.City)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Address)
            </td>
            <td>
              @Html.ActionLink("Edit", "EditEmpDetails", new { id = item.Empid }) |
               @Html.ActionLink("Delete", "DeleteEmp", new { id = item.Empid }
               )
         </td>
        </tr>
  }
</table>
We don't need a JavaScript or jQuery function to show the alert box, you just need to modify the ActionLink in view. The steps are as follows.
@Html.ActionLink("Delete", "DeleteEmp", new { id = item.Empid },
new { onclick = "return confirm('Are sure wants to delete?');" })
In the above ActionLink
  • Delete is the ActionLink Name.  
  • DeleteEmp is the ActionResult name .
  • EmpId is the unquie id from which specific records are deleted. 
After clicking on the delete button, the alert box will be shown as follows.


I hope from all the preceding examples you have learned how to show an alert box Action Link click in ASP.NET MVC.

Related articles

Show Confirm Alert Box

Before deleting records we need show confirm alert box to ensure something should not delete or edit the records accidently. Let us consider following html table which has list of records

<table class="table">
 <tr>
 <th>
 @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.City)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Address)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)

    {
        @Html.HiddenFor(model => item.Empid)
        <tr>
           <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.City)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Address)
            </td>
            <td>
              @Html.ActionLink("Edit", "EditEmpDetails", new { id = item.Empid }) |
               @Html.ActionLink("Delete", "DeleteEmp", new { id = item.Empid }
               )
         </td>
        </tr>
  }
</table>
Now to show alert box just modify the ActionLink in view are as follows
@Html.ActionLink("Delete", "DeleteEmp", new { id = item.Empid },
new { onclick = "return confirm('Are sure wants to delete?');" })
In the above ActionLink
  • Delete is the ActionLink Name.  
  • DeleteEmp is the ActionResult name .
  • EmpId is the unquie id from which specific records are deleted. 
After clicking on delete button the alert box will be shown are as follows


I hope from all preceding examples , you have learned how to show alert box Action Link click in ASP.NET MVC.

Summary

I hope this article is useful for all readers. If you have any suggestion then please contact me.

jQuery Ajax GET Request with Input Parameter in ASP.NET MVC

In many forum post, I have read one common question that is how to make jQuery ajax GET request with input parameter in ASP.NET MVC. So by considering the above requirement, I have decided to write this article.
Let's consider the scenario in which we have an action method named Details in Home controller which takes the Id as an input parameter. Then the jQuery function will look like as follows.
$(document).ready(function () {
        $("#btnGetDetails").click(function () {
            $.ajax({
                //base address/controller/Action
                url: 'http://localhost:51163/Home/Details',
                type: 'GET',
                data: {
                    //Passing Input parameter
                    id: $('#txtId').val()
                },
                success: function (result) {
                   //write something
                },
                error: function () {
                    alert("error");
                }
            });
            return false;
        });
    });
Suppose the Home controller has an action result method named Details which takes id as an input parameter.

HomeController.cs
  public class HomeController : Controller
    {
        
        [HttpGet]
        public ActionResult Details(int id)
        {
        //write logic here to get data

        return View();
        }
    }
Note
  • To work with jQuery, we need to reference the jQuery library. You can use the following CDN jQuery library from any provider such as Microsoft, Google or jQuery.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
To use the above jQuery library, you need an active internet connection. You can download and use it as an offline. You need to add reference as below.
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
From the preceding example we have learned how to make jQuery Ajax GET request with input parameter in ASP.NET MVC.

Summary

I hope this article is useful for all readers. If you have a suggestion related to this article, then please contact me.

How to call JavaScript Alert box from Code behind in Asp.net

The following is the sample code which is used  to call JavaScript Alert box from Code behind in Asp.net

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('This is C#corner')", true);

Summary
I hope this code snippet is useful ,if you have any suggestion regarding this article then please contact me.

Integrating Google MAP With Auto Location Search In ASP.Net

Due to changing business needs and the quick growth of technology, in today's web applications users want many options and capabilities in their applications. So let us learn in this article how to integrate the Google auto-complete search for places in maps.
Google provides many facilities to their users and other developers working on various technologies to integrate their product into applications.
Google Place Autocomplete Map Search
This feature is provided by Google and is in their Google Maps JavaScript API. With it people can enter any place around the world and then the search box will return a list of places in the world depending on that input.
To use the Google Maps Place Autocomplete search of the JavaScript API, use the following methods:
  1. LatLngBounds
  2. fitBounds
  3. getBounds
  4. setBounds
  5. getPlaces
Using the preceding JavaScript methods you can integrate Google Maps Search Places into your application. The following are some of the features of a Google Maps Place Autocomplete search.
Key points for integrating Google Maps:
  1. Google provides the free JavaScript API to integrate Google Maps into our applications.
  2. You can customize Google Maps depending on your requirements.
  3. its provides the suggestion while typing.
Let us see the preceding points with an example by creating a web application using the following:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New WebSite" - "C#" - "ASP.NET Empty Web Application" (to avoid adding a master page).
  3. Provide the web site a name such as "GoogleLocationSearch" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer - "Add New Item" then Default.aspx page.
 Now the Default.aspx source code will look as in the following:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  
<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"  
    Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html>  
  <head>  
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
    <meta charset="utf-8">  
    
    <title>Article by Vithal Wadje</title>  
   
  </head>  
  <body bgcolor="Blue">  
    <h5 style="color:White;">  
        Article for C# corner</h5>  
  
  </body>  
</html>  
Now add one HTML input TextBox control and div tag on the default.aspx page and specify the ID as follows:
    <input id="txtsearch" class="apply" type="text" placeholder="Enter Search Place e.g C# Corner Noida">  
      <div id="divloadMap"></div> 
Now let us add a stylesheet CCS file by right-clicking on the solution and create the following CSS classes:
    html, body,#divloadMap {  
            height: 100%;  
            margin: 0px;  
            padding: 0px;  
            margin-top:15px  
          }  
          
          .apply {  
            margin-top: 16px;  
            border: 1px solid transparent;  
            border-radius: 2px 0 0 2px;  
            box-sizing: border-box;  
            -moz-box-sizing: border-box;  
            height: 32px;  
            outline: none;  
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);  
          }  
      
          #txtsearch {  
            background-color: #fff;  
            padding: 0 11px 0 13px;  
            width: 400px;  
            font-family: Roboto;  
            font-size: 15px;  
            font-weight: 300;  
            text-overflow: ellipsis;  
          }  
      
          #txtsearch:focus {  
            border-color: #4d90fe;  
            margin-left: -1px;  
            padding-left: 14px;    
            width: 401px;  
          }  
      
          .pac-container {  
            font-family: Roboto;  
          }  
      
          #type-selector {  
            color: #fff;  
            background-color: #4d90fe;  
            padding: 5px 11px 0px 11px;  
          }  
      
          #type-selector label {  
            font-family: Roboto;  
            font-size: 13px;  
            font-weight: 300;  
          } 
Now add the JavaScript file to Solution Explorer to call the Google Maps JavaScript API as in the following:
 
Now create the following functions to call the Google Maps API:
    //creating function to load initial MAP when page loading   
    function LoadGoogleMAP() {  
      
        var markers = [];  
        var map = new google.maps.Map(document.getElementById('divloadMap'), {  
            mapTypeId: google.maps.MapTypeId.ROADMAP  
        });  
      
        var defaultBounds = new google.maps.LatLngBounds(  
          new google.maps.LatLng(-33.8902, 151.1759),  
          new google.maps.LatLng(-33.8474, 151.2631));  
        map.fitBounds(defaultBounds);  
      
        // Create the search box and link it to the UI element.  
        var input =(document.getElementById('txtsearch'));  
        map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);  
      
        var searchBox = new google.maps.places.SearchBox((input));  
      
         
        // Listen for the event fired when the user selects an item from the  
        // pick list. Retrieve the matching places for that item.  
        google.maps.event.addListener(searchBox, 'places_changed', function () {  
            var places = searchBox.getPlaces();  
      
            if (places.length == 0) {  
                return;  
            }  
            for (var i = 0, marker; marker = markers[i]; i++) {  
                marker.setMap(null);  
            }  
      
            // For each place, get the icon, place name, and location.  
            markers = [];  
            var bounds = new google.maps.LatLngBounds();  
            for (var i = 0, place; place = places[i]; i++) {  
                var image = {  
                    url: place.icon,  
                    size: new google.maps.Size(71, 71),  
                    origin: new google.maps.Point(0, 0),  
                    anchor: new google.maps.Point(17, 34),  
                    scaledSize: new google.maps.Size(25, 25)  
                };  
      
                // Create a marker for each place.  
                var marker = new google.maps.Marker({  
                    map: map,  
                    icon: image,  
                    title: place.name,  
                    position: place.geometry.location  
                });  
      
                markers.push(marker);  
      
                bounds.extend(place.geometry.location);  
            }  
      
            map.fitBounds(bounds);  
        });  
          
      
          
        // current map's viewport.  
        google.maps.event.addListener(map, 'bounds_changed', function () {  
            var bounds = map.getBounds();  
            searchBox.setBounds(bounds);  
        });  
    }  
      
    google.maps.event.addDomListener(window, 'load', LoadGoogleMAP); 
Now add the stylesheet and JavaScript file reference into the default.aspx page then the default.aspx page entire code will look as follows:
    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
    <%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"  
        Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>  
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
    <html>  
      <head>  
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
        <meta charset="utf-8">  
        
        <title>Article by Vithal Wadje</title>  
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>  
          <script src="GoogleAPIScript.js" type="text/javascript"></script>  
          <link href="MapStyleSheet.css" rel="stylesheet" type="text/css" />  
        
       
      </head>  
      <body bgcolor="Blue">  
        <h5 style="color:White;">  
            Article for C# corner</h5>  
        <input id="txtsearch" class="apply" type="text" placeholder="Enter Search Place e.g C# Corner Noida">  
        <div id="divloadMap"></div>  
      </body>  
    </html> 
 Now run the application. The initial map will look as follows:
 
Now enter a place into the preceding search text box. Let us assume I am searching for MCN solutions, then it gives the following auto-complete search places suggestions:
 
In the preceding example you see that it gives the auto-complete text box while I am searching the places in Google Maps. Now let us enter a city name now; it shows the following suggestions: 
 
Now let us consider I am searching for Noida and after clicking on the suggested text, its shows the location as follows: 
 
From all the preceding examples, we have learned how to integrate Google Maps Auto Location search into an ASP.Net web application.
Notes
  • You need an active internet connection to view Google Maps.
Summary
I hope this article is useful for all readers. If you have any suggestion then please contact me including beginners also.

www.CodeNirvana.in

Protected by Copyscape
Copyright © Compilemode