Thursday, 27 April 2017

Get ID of Last Inserted Record using Entity Framework in ASP.Net MVC


Get ID of Last Inserted Record using Entity Framework
Description:
In this example we explain that how to get the last inserted record using Entity Framework in asp.net mvc or how to get the Id of the last inserted record in MVC using Entity Framework.

Previously we already explain that how to get the last inserted record id in SQL Server but here we explain that how to get the last inserted record or id using Entity Framework in MVC.

Here same we use SCOPE_IDENTITY to fetch the last inserted record id.here we demonstrate when user submit the record then after inserted records Id are displayed in alert box.
Controller:

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(Customer customer)
    {
        using (CustomerEntities entities = new CustomerEntities())
        {
            entities.Customers.Add(customer);
            entities.SaveChanges();
            int id = customer.CustomerId;
        }
        return View(customer);
    }
}
View:

@model EntityFramework_Insert_MVC.Customer

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <table cellpadding="0" cellspacing="0">
            <tr>
                <th colspan="2" align="center">Customer Details</th>
            </tr>
            <tr>
                <td>Name: </td>
                <td>
                    @Html.TextBoxFor(m => m.Name)
                </td>
            </tr>
            <tr>
                <td>Gender: </td>
                <td>
                    @Html.DropDownListFor(m => m.Country, new List<SelectListItem>
                   { new SelectListItem{Text="India", Value="India"},
                     new SelectListItem{Text="Pakistan", Value=" Pakistan"},
                     new SelectListItem{Text="UK", Value="UK"},
                     new SelectListItem{Text="Canada", Value="Canada"}},
                     "Please select")
                </td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Submit"/></td>
            </tr>
        </table>
    }

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    @if (Model != null)
    {
        <script type="text/javascript">
            $(function () {
                alert("Inserted Customer ID: " + @Model.CustomerId);
            });
        </script>
    }
</body>
</html>


This entry was posted in :

0 comments:

Post a Comment