Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

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