Registration page using Jquery in asp.net mvc ~ MiTechDev.com

Mitechdev.com is a programming blog which focused on Web Programming and development

Friday, 25 August 2017

Registration page using Jquery in asp.net mvc

03:59:00 Posted by raviteja swayampu , No comments
Hi every one in this we gonna implement Registration page in asp.net mvc website.We already learn how to implement registration,login page using angular js in asp.net website in this blog.
1.Registration page using angular js
2.Login page using angular js
In this tutorial we gonna implement registration page using Jquery. In real time application development it is not possible to implement model binding every where in web application.In case of a web page contains multiple forms,dynamic forms we go for jquery to save data from front end to database.Now lets see in step by step manner.

Registration page using Jquery in asp.net mvc

1.Create a asp.net mvc web project by select empty mvc template.

2.Add a database in AppData folder and create a table and name it as Customer.
3.Database script is as follows..
CREATE TABLE [dbo].[Customer] (
    [Id]                INT           IDENTITY (1, 1) NOT NULL,
    [Name]              NVARCHAR (50) NOT NULL,
    [UserName]          NVARCHAR (50) NOT NULL,
    [Password]          NVARCHAR (50) NOT NULL,
    [Email]             NVARCHAR (50) NOT NULL,
    [Contact]           BIGINT        NOT NULL,
    [Gender]            NVARCHAR (10) NOT NULL,
    [Country]           NVARCHAR (20) NOT NULL,
    [ConfirmNewsLetter] BIT           NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);
4.Add Entity data model in models folder.
  a) Go to Solution Explorer --> Models folder-- > Add --> New item --> Select ADO.net Entity Data       Model under data --> Enter model name --> Add.
  b) A popup window will come (Entity Data Model Wizard) --> Select Generate from database -->           Next -->Chose your data connection --> select your database-- > next --> Select tables -->
     enter Model Namespace --> Finish.
5.Add controller and name it as HomeController and add Index() action method to render Index.cshtml page.SaveRecords() to save the records to database.
HomeController.cs:
public class HomeController : Controller
    {
        public ActionResult Index()
        {
            List _list = new List()
            {
                new SelectListItem {Text="--Select Country--" ,Value="" },
                new SelectListItem {Text="India",Value="India" },
                new SelectListItem {Text="Jermany",Value="Jermany" },
                new SelectListItem {Text="USA",Value="USA" },
                new SelectListItem {Text="Russia",Value="Russia" },
                new SelectListItem {Text="Japan",Value="Japan" }
            };
            ViewBag.Country = _list;
            return View();
        }
        public JsonResult SaveRecords(Customer customer)
        {
            bool result = false;
            if (customer != null)
            {
                using (DatabaseEntities db=new DatabaseEntities())
                {
                    db.Customers.Add(customer);
                    db.SaveChanges();
                    result = true;
                }
            }
            return Json(result,JsonRequestBehavior.AllowGet);
        }
    }
6.Now to add view to index action method by right click on index action and add view.
7.Below is the index view code after some design modification done.

Index.cshtml:
@model RegistrationUsingJquery.Models.Customer

@{
    ViewBag.Title = "Index";
}
<script type="text/javascript">
    var url = "@Url.Action("SaveRecords","Home")";
</script>
<script src="~/Scripts/app.js"></script>
@using (Html.BeginForm())
{
    <div class="form-horizontal">
        <h4 class="text-info">Registration Using Jquery</h4>
        <hr />
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger", id = "spnName" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.UserName, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.UserName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.UserName, "", new { @class = "text-danger",id="spnUserName" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control"} })
                @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger",id="spnPassword" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Email, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger", id = "spnEmail" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Contact, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Contact, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Contact, "", new { @class = "text-danger", id = "spnContact" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.RadioButtonFor(model=>model.Gender,"Male")<label>Male</label>
                @Html.RadioButtonFor(model => model.Gender, "Female")<label>Female</label>
                @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger", id = "spnGender" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Country, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("Country",ViewBag.Country as List<SelectListItem>,new { @class="form-control"})
                @Html.ValidationMessageFor(model => model.Country, "", new { @class = "text-danger", id = "spnCountry" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ConfirmNewsLetter, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <div class="checkbox">
                    @Html.EditorFor(model => model.ConfirmNewsLetter)
                    @Html.ValidationMessageFor(model => model.ConfirmNewsLetter, "", new { @class = "text-danger", id = "spnConfirmNewsLetter" })
                </div>
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="button" onclick="SaveRecord();" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}
registration-page-using-jquery-in-asp.netmvc-mitechdev.com

Add Jquery script code to validate and save data in DB

8.Right click on scripts --> add javascript file--> name it as app.js.
9.Enter below script code in app.js file.


//Form validation function
function validateform() {
    var result = true;
    var emailReg = /^([\w-\.][email protected]@([\w-]+\.)+[\w-]{2,4})?$/i;
    var phoneReg = /([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})/;

    if ($("#Name").val() == "") {
        $("#spnName").text("Full Name Required");
        result = false;
    } else {
        $("#spnName").text("");
    }
    if ($("#UserName").val() == "") {
        $("#spnUserName").text("UserName Required");
        result = false;
    } else {
        $("#spnUserName").text("");
    }
    if ($("#Password").val() == "") {
        $("#spnPassword").text("Password Required");
        result = false;
    } else {
        $("#spnPassword").text("");
    }
    if ($("#Email").val() == "") {
        $("#spnEmail").text("Email Required");
        result = false;
    }
        //validating email with regular expression
    else if (!emailReg.test($.trim($("#txtEmail").val()))) {
        $("#spnEmail").text("Valid Email Required");
        result = false;
    } else {
        $("#spnEmail").text("");
    }
    if ($("#Contact").val() == "") {
        $("#spnContact").text("Contact Required");
        result = false;
    }
        //validating phone number with regular expression
    else if (!phoneReg.test($.trim($("#Contact").val()))) {
        $("#spnContact").text("Valid Contact Required");
        result = false;
    } else {
        $("#spnContact").text("");
    }
    //validating radio button checked or not
    if (!$("input[name='Gender']:checked").val()) {
        $("#spnGender").text("Select Gender");
        result = false;
    } else {
        $("#spnGender").text("");
    }
    //validating checkbox
    if ($("#ConfirmNewsLetter").prop('checked') == false) {
        $("#spnConfirmNewsLetter").text("Select Policy");
        result = false;
    } else {
        $("#spnConfirmNewsLetter").text("");
    }
    //validating dropdownlist
    if ($("#Country").val() == "") {
        $("#spnCountry").text("Select country");
        result = false;
    } else {
        $("#spnCountry").text("");
    }
    return result;
}

function SaveRecord() {
    if (validateform()) {
        var customer = {
            Name: $("#Name").val(),
            UserName: $("#UserName").val(),
            Password: $("#Password").val(),
            Email: $("#Email").val(),
            Contact: $("#Contact").val(),
            Gender: $("input[name='Gender']:checked").val(),
            Country: $("#Country").val(),
            ConfirmNewsLetter: $("#ConfirmNewsLetter").val()
        };
        $.post(url, { customer: customer }, function (data) {
            if (data == true) {
                alert("Record inserted successfully");
            }
            else {
                alert("Record insertion failed");
            }
        });
    }
}
10.Here, validateform() method validates the form.SaveRecord() method sends the for data to server to save in database.in above code i created customer object to hold form data.here we can use a form collection object also but Form collection object sends all elements of form including unnecessary elements also.So,it is a wast of memory that's why i created a java script object here.
Note: The fields of java script object(customer in above script code) and properties of the receiving object in controller action method must be same(SaveRecord(Customer customer) action method).
11.I performed validations for this form using jquery.Click here to know how to implement jquery validations on real time web applications.We can also implement validations using data annotations also.
12.The records inserted in database are look like below.
Download source code for this applications Download(VS2015)

registration-page-using-jquery-in-asp.netmvc-mitechdev.com

Conclusion:

I hope this tutorial will help you .To get more updates please subscribe to this blog subscribe. OR follow on Social networks for daily awesome updates[Facebook,twitter,google plus].

0 comments:

Post a Comment