Showing posts with label ASP.Net MVC. Show all posts
Showing posts with label ASP.Net MVC. Show all posts

Friday, January 10, 2014

Execute Stored Procedure using Entity Framework in ASP.NET MVC

In this article we are going to see how to execute the stored procedure in entity framework ,In MVC we are going to see the how to add the EF.

Execute the following script in the database to create a stored procedure.

CREATE PROCEDURE FETCHEMPLOYEES
AS
BEGIN
      SELECT * FROM EMPTABLE
END

CREATE PROCEDURE FETCHEMPLOYEE(@ID INT)
AS
BEGIN
      SELECT * FROM EMPTABLE WHERE ID = @ID
END



Create a Empty MVC project, select Razor as Engine. Right click the Models and add new item.Select Data in the left pane and click ADO.NET entity framework model.Give a name as Employee.edmx and press ok.




Choose the model content as Generate from the database,and click next.




 Now select the New Connection and give the Entities name, then click next. 




Then select the all stored procedure which are need for the project. Give the model name as Employee Model and click Finish.




Right click the Employee.edmx and click the model browser to see the following items.




Expand the EmployeeModel.Store and select the stored procedure and the Tables need to be in project. that need to be added in entities.and click add Function Import to import the stored procedure as Function to the code.




In the Add Function Import screen please give the function name as you need and select the return type of that stored procedure based on your requirement. In this project return type is a emptable value , if your are returning a complex type by combining a multiple tables. The entities that are seen in the collection is listed by selected what are selected in the tables in the EmployeeModel.edmx.



Now add a cs file as Empmodel.cs in the Models folder to iterate values from db through stored procedure.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;

namespace EFSample.Models
{
    public class EmpModel
    {
        EmployeeEntities empdb = new EmployeeEntities();
       
        public List<EMPTABLE> GetEmployees()
        {
           return empdb.FETCHEMPLOYEES().ToList();  
        }

        public EMPTABLE GetEmployee(int? id)
        {
            return empdb.FETCHEMPLOYEE(id).ToList().Single();
        }
    }
}
  

Add the EmployeeController 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EFSample.Models;

namespace EFSample.Controllers
{
    public class EmployeeController : Controller
    {
        Models.EmpModel mod = new Models.EmpModel();

        public ActionResult Index()
        {
            List<EMPTABLE> result = mod.GetEmployees();
            return View(result);
        }

        public ActionResult Details(int id)
        {
            EMPTABLE result = mod.GetEmployee(id);
            return View(result);
        }

    }
}



Add the Index View and Details View.

Index.cshtml
@model IEnumerable<EFSample.Models.EMPTABLE>

@{
    ViewBag.Title = "Employee Information";
}

<h2>Employees</h2>

<p>
    @Html.ActionLink("Create New""Create")
</p>
<table style="border:2px solid Pink">
    <tr>
        <th style="color:Blue">
            @Html.DisplayNameFor(model => model.NAME)
        </th>
        <th style="color:Blue">
            @Html.DisplayNameFor(model => model.DEPTID)
        </th>
        <th style="color:Blue">
            @Html.DisplayNameFor(model => model.COUNTRY)
        </th>
        <th style="color:Blue">
            @Html.DisplayNameFor(model => model.MARRIED)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.NAME)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.DEPTID)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.COUNTRY)
        </td>
       
        <td>           
            @Html.ActionLink("Details""Details"new { id=item.ID })        
        </td>
    </tr>
}

</table>



Details.cshtml
@model EFSample.Models.EMPTABLE

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>
<link href="../../Site.css" rel="stylesheet" type="text/css" />
<fieldset>
    <legend>EMPTABLE</legend>

   
    <table>
   
    <tr>
    <td>  @Html.DisplayNameFor(model => model.NAME) :</td><td style="font-weight:bold">@Html.DisplayFor(model => model.NAME)</td>   
    </tr>
   
    <tr>
    <td> @Html.DisplayNameFor(model => model.DEPTID) :</td><td style="font-weight:bold"> @Html.DisplayFor(model => model.DEPTID)</td>
    </tr>

    <tr>
    <td>  @Html.DisplayNameFor(model => model.COUNTRY) :</td><td style="font-weight:bold">@Html.DisplayFor(model => model.COUNTRY)</td>
    </tr>
   
    </table>                 

</fieldset>
<p>
    @Html.ActionLink("Edit""Edit"new { id=Model.ID }) |
    @Html.ActionLink("Back to List""Index")
</p>


Output:

Index.View



 Details.View




From this article you can learn how to add the stored procedure as function in the Model using Entity Framework in ASP.NET MVC.



Sunday, January 5, 2014

Remote Validation - Check the user existence in people register form ASP.NET MVC




In this article we are going to see how to validate the textbox value whether it is already exists,In real time we can see that user name already exist error,now we are going to implement this, For do that first we have to Create a Table and Create a model using Database first using Entity Framework.

Sql Script:
create tablePeople
(
id int identity(1,1),
name varchar(30),
contact varchar(10),
addr varchar(200),
occupation varchar(100)
)

INSERT INTOPeople(
                  name,
                  contact,
                  addr,
                  occupation
                  )
VALUES            (
                  'Rajesh',
                  '1234567',
                  'Porur',
                  'Enterprenur'
                  )

INSERT INTOPeople(
                  name,
                  contact,
                  addr,
                  occupation
                  )
VALUES            (
                  'Suresh',
                  '84748467',
                  'Porur',
                  'Software Engineeer'

                  )

After creating the script create a model by right click the project and add the new item of ado.net edmx and fetch the all tables present in particulaer database.Now see the designer file you can see the template.

  [Serializable()]
    [DataContractAttribute(IsReference=true)]
    public partial class Person : EntityObject
    {
        #regionFactory Method
   
        /// <summary>
        /// Create a new Person object.
        /// </summary>
        /// <param name="id">Initial value of the id property.</param>
        public static Person CreatePerson(global::System.Int32 id)
        {
            Person person = newPerson();
            person.id = id;
            return person;
        }

        #endregion
        #regionPrimitive Properties
   
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
        [DataMemberAttribute()]
        public global::System.Int32 id
        {
            get
            {
                return _id;
            }
            set
            {
                if (_id != value)
                {
                    OnidChanging(value);
                    ReportPropertyChanging("id");
                    _id = StructuralObject.SetValidValue(value);
                    ReportPropertyChanged("id");
                    OnidChanged();
                }
            }
        }
        private global::System.Int32 _id;
        partial voidOnidChanging(global::System.Int32 value);
        partial voidOnidChanged();
   
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
        [DataMemberAttribute()]
        public global::System.String name
        {
            get
            {
                return _name;
            }
            set
            {
                OnnameChanging(value);
                ReportPropertyChanging("name");
                _name = StructuralObject.SetValidValue(value, true);
                ReportPropertyChanged("name");
                OnnameChanged();
            }
        }
        private global::System.String _name;
        partial voidOnnameChanging(global::System.String value);
        partial voidOnnameChanged();
   
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
        [DataMemberAttribute()]
        public global::System.String contact
        {
            get
            {
                return _contact;
            }
            set
            {
                OncontactChanging(value);
                ReportPropertyChanging("contact");
                _contact = StructuralObject.SetValidValue(value, true);
                ReportPropertyChanged("contact");
                OncontactChanged();
            }
        }
        private global::System.String _contact;
        partial voidOncontactChanging(global::System.String value);
        partial voidOncontactChanged();
   
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
        [DataMemberAttribute()]
        public global::System.String addr
        {
            get
            {
                return _addr;
            }
            set
            {
                OnaddrChanging(value);
                ReportPropertyChanging("addr");
                _addr = StructuralObject.SetValidValue(value, true);
                ReportPropertyChanged("addr");
                OnaddrChanged();
            }
        }
        private global::System.String _addr;
        partial voidOnaddrChanging(global::System.String value);
        partial voidOnaddrChanged();
   
        /// <summary>
        /// No Metadata Documentation available.
        /// </summary>
        [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
        [DataMemberAttribute()]
        public global::System.String occupation
        {
            get
            {
                return _occupation;
            }
            set
            {
                OnoccupationChanging(value);
                ReportPropertyChanging("occupation");
                _occupation = StructuralObject.SetValidValue(value, true);
                ReportPropertyChanged("occupation");
                OnoccupationChanged();
            }
        }
        private global::System.String _occupation;
        partial voidOnoccupationChanging(global::System.String value);
        partial voidOnoccupationChanged();

        #endregion
   
    }
 




Now create a another partial class with same name, Now override the name with custom display name remote validation and bind the action and controller for remote validation like existence of user name.


    [MetadataType(typeof(PersonMetaData))]   
    public partial class Person
    {

    }

    public class PersonMetaData
    {
        [Remote("Register", "Human", ErrorMessage = "User Name Already Exists")]
        [DisplayName("UserName")]
        public string name { set; get; }
             
    }

Controller:
PersonEntities datas = new PersonEntities();

        public ActionResult Index()
        {
            returnView(datas.People.ToList());
        }

        public JsonResult Register(stringname)
        {           
            returnJson(!datas.People.Any(x => x.name == name),JsonRequestBehavior.AllowGet);           
        }

        public ActionResult Create()
        {
            returnView();
        }



View :

Create.cshtml
@model EastSolution.Models.Person

@{
    Layout = null;
}

<!DOCTYPEhtml>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Create</title>
    <link href="../../Content/Site.css" rel="stylesheet"type="text/css"/>
</head>
<body>
    <script src="~/Scripts/jquery-1.7.1.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
   
    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)
   
        <fieldset style="width:500px;margin-left: 298px;margin-top: 58px;margin-bottom:50px">
            <legend>People Registry</legend>
   
            <div class="editor-label">
                @Html.LabelFor(model => model.name)
            </div>
            <divclass="editor-field">
                @Html.EditorFor(model => model.name)
                @Html.ValidationMessageFor(model => model.name)
            </div>
   
            <div class="editor-label">
                @Html.LabelFor(model => model.contact)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.contact)
                @Html.ValidationMessageFor(model => model.contact)
            </div>
   
            <div class="editor-label">
                @Html.LabelFor(model => model.addr)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.addr)
                @Html.ValidationMessageFor(model => model.addr)
            </div>
   
            <div class="editor-label">
                @Html.LabelFor(model => model.occupation)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.occupation)
                @Html.ValidationMessageFor(model => model.occupation)
            </div>
   
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    }
   
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
</body>
</html>




Index.cshtml

@model IEnumerable<EastSolution.Models.Person>

@{
    Layout = null;
}

<!DOCTYPEhtml>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link href="../../Content/Site.css" rel="stylesheet"type="text/css"/>
</head>
<body>
    <p style="width:500px;margin-left: 298px;margin-top: 58px;margin-bottom:40px">
        @Html.ActionLink("Create New", "Create")
    </p>
    <table style="width:500px;margin-left: 298px;margin-top: 58px;">   
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.name)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.contact)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.addr)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.occupation)
            </th>
            <th></th>
        </tr>
   
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.contact)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.addr)
            </td>
            <td style="padding:2px">
                @Html.DisplayFor(modelItem => item.occupation)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new{ id=item.id }) |
                @Html.ActionLink("Details", "Details", new { id=item.id }) |
                @Html.ActionLink("Delete", "Delete", new{ id=item.id })
            </td>
        </tr>
    }
   
    </table>
</body>

</html>


Output:


From this article you can learn how to create the remote validation in asp.net MVC