Pages

How to save Data using Ajax and jquery in asp.net

Wednesday, 12 November 2014

This article will demonstrate how to save record using ajax and jquery in asp.net.
Step 1- Create a new empty website.
Step 2- Add a new web form .
Step 3- Write down the following code to your web form.

<form id="form1" runat="server">
     <div>
        <table>
            <tr>
                <td>
                    Name
                </td>
                <td>
                    <input type="text" id="txtName" />
                </td>
            </tr>
            <tr>
                <td>
                    Position
                </td>
                <td>
                    <input type="text" id="txtPosition" />
                </td>
            </tr>
            <tr>
                <td>
                    Age
                </td>
                <td>
                    <input type="text" id="txtAge" />
                </td>
            </tr>
            <tr>
                <td>
                    Salary
                </td>
                <td>
                    <input type="text" id="txtSalary" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <input type="button" onclick="SaveData();" value="Save" />
                </td>
            </tr>
        </table>
    </div>
    </form>


Step 4- Write down the following JS Code .

function SaveData() {
            var errMsg = '';
            var name = $('#txtName').val().trim();
            var position = $('#txtPosition').val().trim();
            var age = parseInt($('#txtAge').val().trim());
            var salary = parseInt($('#txtSalary').val().trim());
            $.ajax({
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                url: 'Index.aspx/SaveData',
                data: "{ 'Name':' " + name + "', 'Position':' " + position + "', 'Age':' " + age + "', 'Salary':' " + salary + "' }",
                success: function (data) {
                    alert(data.d);
                    clearAll();
                },
                error: function (data) {
                    alert(data.d);
                }
            });
        }
        function clearAll() {
            $('#txtName').val('');
            $('#txtPosition').val('');
            $('#txtAge').val('');
            $('#txtSalary').val('');
        }
Step 5- As Ajax is caliing SaveData WebMethod . so write down the webmethod in code behind (Index.aspx.cs)

 [WebMethod]
    public static string SaveData(string Name, string Position, int Age, int Salary)
    {
        string str = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
        string msg = "";
        try
        {
            SqlConnection con = new SqlConnection(str);
            con.Open();
            SqlCommand cmd = new SqlCommand("insert into Employee values (@1,@2,@3,@4)", con);
            cmd.Parameters.Add("@1", Name);
            cmd.Parameters.Add("@2", Position);
            cmd.Parameters.Add("@3", Age);
            cmd.Parameters.Add("@4", Salary);
            cmd.ExecuteNonQuery();
            con.Close();
            msg = "Record Inserted";
        }
        catch (Exception ex)
        {
            msg = "Record Not Inserted" + ex.Message;
        }

        return msg;
    }


Note: Download above code Download

Read more ...

How to delete multiple records from webgrid in mvc

Tuesday, 11 November 2014
In this post, I'll explain how to delete multiple record from webgrid .
Step 1- Create a new empty mvc project.
Step 2- Add Model class Employee and Context Class to model folder.
public class Employee
    {
        [Key]
        public int ID { get; set; }
        public string Name { get; set; }
        public string Position { get; set; }
        public int Age { get; set; }
        public int Salary { get; set; }
    }
public class DemoContext:DbContext
    {
        public DbSet<Employee> Employee { get; set; }
    }

Step 3- Add a new controller and write the following to populate webgrid
 public class HomeController : Controller
    {
        DemoContext _db = new DemoContext();
        public ActionResult Index()
        {
            var getData=_db.Employee.ToList();
            return View(getData);
        }
    }

step 4- Build the solution then add a strongly typed view name as Index. write down following code to your view
@model IEnumerable<MultipleDelete.Models.Employee>


@{
    ViewBag.Title = "Index";
    var grid = new WebGrid(source: Model, rowsPerPage: 5);
}
<h2>Employee List</h2>
<div id="divList">
    @using(Html.BeginForm("DeleteSelected", "Home",FormMethod.Post))
    {
        @grid.GetHtml(
    columns:
        grid.Columns(
               grid.Column(format: @<text><input type="checkbox" name="Eid" value="@item.ID" /></text>, header: ""),
                grid.Column("ID", "ID"),
                grid.Column("Name", "Name"),
                grid.Column("Position", "Position"),
                grid.Column("Age", "Age"),
                grid.Column("Salary", "Salary")
            )
        )
        <input type="submit" value="Delete" />
    }
</div>

Step -5 Add a Action to your controller which delete selected records.
         [HttpPost]
        public ActionResult DeleteSelected(string[] Eid)
        {
            var SelectCount=Eid.Length;
            List<int> selectedIds=new List<int>();
            foreach (var d in Eid)
            {
                selectedIds.Add(Convert.ToInt32(d));
            }
            IList<Employee> selectedEmployee = new List<Employee>();
            selectedEmployee = _db.Employee.Where(n => selectedIds.Contains(n.ID)).ToList();
            foreach(var singleEmp in selectedEmployee)
            {
                _db.Employee.Remove(singleEmp);
            }
            _db.SaveChanges();
            return RedirectToAction("Index");
        }

what I'm doing in above action is as follow

First I got the array of string of ID's from posted form, then I converted it into int array.

Then I get the list of employee from corresponding Id's , then using foreach loop I have deleted it one by one.

Click Here to get Above Code Download

Read more ...

CRUD operation in mvc using jquery and ajax Part 1

Monday, 10 November 2014
This article will demonstrate how to perform CRUD operation in mvc using Entity Framework and Ajax.

Step 1- Create Empty MVC project.

Step 2- Create DataModel and DataContext Class.

using System.ComponentModel.DataAnnotations;

namespace MVCdataTables.Models
{
    public class Employee
    {
        [Key]
        public int ID { get; set; }
        public string Name { get; set; }
        public string Position { get; set; }
        public int Age { get; set; }
        public int Salary { get; set; }
    }
}

using System.Data.Entity;
namespace MVCdataTables.Models
{
    public class DemoDataContext:DbContext
    {
        public DbSet<Employee> Employee { get; set; }
    }
}

Step 2- Create a Controller Name as Home. and add the following method. Here GetEmployee will return list of employee.
public ActionResult Index()
        {
            return View();
        }
        public IList<Employee> GetEmployee()
        {
            IList<Employee> getData = _db.Employee.ToList();
            return getData;
        }

Step 3- For read operation, create a function in your controller which will json
 public JsonResult GetData()
        {
            return Json(GetEmployee());
        }

Step 4- Write following Js code to bind Employee table in your view
$(document).ready(function () {
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: '/Home/GetData',
        dataType: "json",
        success: function (data) {
            BindTable(data);
        },
        error: function (data) {
            alert(data);
        }
    });
});

function BindTable(data) {
  var tabHtml = '';
  $.each(data, function (i, d) {
  tabHtml += "<tr><td><span class='hide'>" + d.ID + "</span>" + d.Name +"+</td>
    <td>" + d.Position + "</td><td>" + d.Age + "</td><td>" + d.Salary + "</td>"+"<td>
    <span class='Edit ML10'>Edit</span><span class='Delete ML10'>Delete</span> </tr>";
    });
    $('#dbTable').find('tbody').html(tabHtml);
    $('#dbTable').dataTable();
}

Step 5- Write following code in your view to show employee list in table.
<table id="dbTable" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
    <tr>
        <th>Name</th>
        <th>Position</th>
        <th>Age</th>
        <th>Salary</th>
        <th>Action</th>
    </tr>
</thead>
    <tbody>
        
    </tbody>
</table>

step 6- Delete Operation. Write down following js .on click event of delete read the corresponding Employee .
$(document).delegate('.Delete', 'click', function () {
    var getId = parseInt($(this).closest('tr').find('td:eq(0)').find('span').text());
    BootstrapDialog.confirm('Are you sure you want to delete person?', function (result) {
            if (result) {
                $.ajax({
                    type: 'GET',
                    contentType: 'application/json; charset=utf-8',
                    url: '/Home/DeleteData',
                    data: { Id: getId },
                    dataType: "json",
                    success: function (response) {
                        BindTable(response)
                    },
                    error: function (response) {
                        alert("Error In Deleting Person ");
                    }
                });
            }
        });
    });
Step 7- write down function in your controller to delete employee
 public JsonResult DeleteData(int Id)
        {
            var getPerson = _db.Employee.Find(Id);
            if (getPerson != null)
            {
                _db.Employee.Remove(getPerson);
                _db.SaveChanges();
            }
            return Json(GetEmployee(), JsonRequestBehavior.AllowGet);
        }



Note: You can download Js and Controller code from here Download
Read more ...

How To Create Custom Html Helper In MVC

Saturday, 8 November 2014
A Html helper just a method which returns a string having string or plain text, which can be used in our view . We have In-built html helper like Html.ActionLink(), Html.TextBox().

In this article we will try to understand , How to create own custom html helper in MVC.
Let's create a new mvc application.

Step 1 - Create a new mvc application , name as "CustomHelperDemo".

Step 2 - Add a new class post to model folder.

public class Post
    {
       public virtual int Id{ get; set; }
        public virtual string Title{ get; set; }
        public virtual DateTime PostedOn{ get; set; }
        public virtual string Category  {get;set;}
    }

Step 3 - Add a new class ActionLinkHelpers to create custom HTML helper using extension method.

public static class ActionLinkHelpers
{
 public static MvcHtmlString PostsLink(this HtmlHelper htmlHelper, Post post)
        {
            return htmlHelper.ActionLink(post.Title, "Blog", "Home",
                new
                {
                    year = post.PostedOn.Year,
                    month = post.PostedOn.Month,
                    category = post.Category
                },
                new
                {
                    Title = post.Title,
                    Id = post.Id
                });
        }
    }
Step 4 - Build the project, and include below code in view where do you want to use your custom class.

@using CustomHelperDemo

But if you want to use across all over the view without inckuding "@using CustomHelperDemo" then you have to add namespace in View's Web.config

<add namespace="CustomHelperDemo"/>

And now you can use your own custom html helper in your view.
@model CustomHelperDemo.Post

@Html.PostsLink(Model)
Read more ...