Simple registration page based on MVC4+EF5.0+Ajax+Json+CSS3 (get& post)

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Using mvc4 can quickly create a page, but the package is too much, there will inevitably be some performance problems. So based on this, through the use of hand written HTML, simple ajax, JSON to create a registration page, will be relatively clean, concise.

In this project, the environment is MVC4+EF5.0+JQuery1.8.2+VS2013

The first effect chart:

ajax jsonpost数据

To create such a registration page, divided into the following steps

1,Create a page HTML

2,JS validation of user input data

3,Json+ajax get data verify that the user name

4,Json+ajax post data are presented to the user registration information

5,CSS3 beautify the page

The following specific implementation process began to describe:

1,Create a page HTML

Add a view, named Index.cshtml, the following HTML code into:

<body>
        <div id="background">
            <h1 id="logo">flowbywind</h1>
            <div id="content">
                <h2>Registration</h2>
                  <fieldset>
                      <label for="userName">User name</label><span class="required">*</span>
                      <input name="userName"  type="text" id="userName"/>
                  </fieldset> 
                <fieldset>
                    <label for="userPwd">Cipher</label><span class="required">*</span>
                    <input name="userPwd" type="password" id="userPwd"/>
                </fieldset>
                <fieldset>
                    <label for="userPwd2">Confirm password</label><span class="required">*</span>
                    <input name="userPwd2" type="password" id="userPwd2" />
                </fieldset>
                <fieldset>
                    <label for="The mailbox">The mailbox</label><span class="required">*</span>
                    <input name="userEmail" type="text" id="userEmail"/>
                </fieldset>
                <fieldset class="nolabel">
                    <input type="button"  id="register" value="Registration" />
                </fieldset>
            </div>
        </div>
    </body>

2,JS validation of user input data

Validate user input data are mainly concentrated in the user name already exists, the password and the password are the same, the mailbox format with the rules

First, we build a tool like util.js, which is mainly used to verify that the data is empty, mailbox format, display the error warning and cancel the warning and other public method

If this judgment method of control data is empty:

//Judge whether the input is a null value control 
//The e parameter here if you don't pass it, the default is the event object, through this event object, can obtain the object triggering events
function fieldIsFilled(e)
{
    var me = getActiveObject(e); //Gets the object triggering events 
    if (me.value == "") {
        //display an error
        warn(me, "required");
    }
    else {
        //cancle display error
        unwarn(me, "required");
    }
}
The getActiveObject function in the above method, is mainly to consider the browser compatibility, as follows: 
///To obtain the object triggering events
///To handle multiple event handlers in IE does not support the this object triggering events
function getActiveObject(e)
{
    var obj;
    if (!e)  // Sending an earlier version of IE is not such an object can only be obtained through the window.event property of event object 
    {
        obj = window.event.srcElement;
    }
    else if (e.srcElement)  //IE 7 or later
    {
        obj = e.srcElement;
    }
    else {
        obj = e.target; //SupportThe DOM Level 2 browser (chrome Firefox Opera) provides the current object through the target property of the incoming event
    }
    return obj;
}
There is a warn and unwarn two method of the above method, the two methods were used to control the display error warning and cancel the warning role. 
The warn code is as follows: 
Support dynamic error adding content to the HTML page, that is if the user input data is not valid, then the new P elements, P elements display error, whereas unwarn method, is the P element removes the HTML page. 
    //Display is not legitimate cause for the field object warningType user input data in userRegister.js is required, IsExist etc. 
function warn(field, waringType) {
    var parentNode = field.parentNode; //The parent node for the current object 
    //Calculation of JSON data using Eval (such as warnings.userName.required in userRegister.js instructions for the user name cannot be empty) made the error message content
    var warning = eval("warnings." + field.id + "." + waringType);
    //Judge P elements of the parent nodes below is present, the P element is used to display the error, if it does not exist, then generate the P element to the parent node. 
    if (parentNode.getElementsByTagName("p").length == 0) {
        var p = document.createElement("p");
        field.parentNode.appendChild(p);
        var warningNode = document.createTextNode(warning); 
        p.appendChild(warningNode);
    }
        //If the P already exists, then updates the current error
    else {
        var p = parentNode.getElementsByTagName("p")[0]; 
        p.childNodes[0].nodeValue = warning; //The first child node P childNodes[0] represents the P text nodes, text node nodeValue is the text value
    }
}


Here, warning is a global variable declaration is a JSON data, stored data items each control:

var warnings = {
    "userName": {
        "required": "The user name cannot be empty",
        "IsExist":"This user name already exists, please input again"
    },
    "userPwd2": {
        "required": "Password should not be empty",
        "isEqual": "You must enter the same password two times"
    },
    "userPwd": {
        "required": "Password should not be empty",
    },
    "userEmail": {
        "required": "Mailbox cannot be empty",
        "format":"The mailbox is not in the correct format, sample: ''"    },
    "register": ""
}

In order to achieve the real-time response to the user input data is valid, in the page initialization bind monitoring events, in the user after the input trigger data check:

window.onload = initPage;
   //Initialize the page, to control events, the multiple event handlers, which controls a will perform multiple events
function initPage(){
    //AddEventHandler is monitoring events according to the selective call addEventListener (using the Chrome browser Firefox) or attachEvent (for IE) method
    addEventHandler(document.getElementById("userName"), "blur", fieldIsFilled);  //Multiple event handler
    addEventHandler(document.getElementById("userName"), "blur", checkUserName);
    addEventHandler(document.getElementById("userPwd"), "blur", fieldIsFilled);
    addEventHandler(document.getElementById("userPwd2"), "blur", fieldIsFilled);
    addEventHandler(document.getElementById("userPwd2"), "blur", checkPwdEqual);
    addEventHandler(document.getElementById("userEmail"), "blur", emailIsProper);
    addEventHandler(document.getElementById("userEmail"), "blur", fieldIsFilled);
    document.getElementById("register").onclick = submitData;
};

3,Json+ajax get data verify that the user name

The following talk about using json+ajax get data, to verify a username, which verify the name of user input is already registered.

//The user name is repeated detection
function checkUserName() {
    jQuery.ajax({
        url: "register/validateUser",
        type: "GET",
        data: { "userName": $("#userName").val() },
        contentType: "application/x-www-form-urlencoded",
        success: function (data) {
            if (data == "false") {
                warn(document.getElementById("userName"), "IsExist");
            }
            if (data == "ok") {
                unwarn(document.getElementById("userName"), "IsExist");
            }
        },
        error: function (xhr, error, ex)
        {
            var div = document.createElement("div");
            div.innerText =  "Error, please try again later, the inconvenience, please understanding";
            document.getElementsByTagName("body")[0].appendChild(div);
        }
    });
    //Using the jQuery Ajax request to send
}

The code corresponding to the background:

public string ValidateUser(string userName)
        {
            using(LoginDbContext db=new LoginDbContext())
            {
                //If the current user name already exists to return false
            if (db.UserRegisters.Where(a=>a.UserName==userName ).Count()>0)
            {
                return "false";
            }
            else
            {
                return "ok";
            }
            }
        }

4,Json+ajax post data are presented to the user registration information

The use of ajax+json post in the MVC data, several points that should be noted:

1)Modify the contentType to "application/json", send data using the JSON.stringfy (the JS object); JSON.stringfy is the role of the object JSON formatted string, just the opposite of JSON.parse, JSON.parse is the string JSON is parsed into an object.

The JS entity object is constructed according to the entity attributes, as follows:

function userRegisterModel() {
    var self = this;
    this.UserName = $("#userName").val();
    this.UserPwd = $("#userPwd").val();
    this.UserEmail = $("#userEmail").val();
}

Then using Ajax to submit data,

var request = new userRegisterModel();
    $.ajax(
        {
            url: "Register/Register",
            type: "POST",
            dataType: "json",
            data: JSON.stringify(request),
            contentType: "application/json",
            success: function (data) {
                if (data.result == "success") {
                    warnings["register"]["register"] = data.content;
                    warn(document.getElementById("register"), "register");
                }
                if (data.result == "error") {
                    warnings["register"]["register"] = data.content;
                    warn(document.getElementById("register"), "register");
                }
            }
        }
        );

Background processing code corresponding to the:

        [HttpPost]
        public JsonResult Register(UserRegister model)
        {
            using (LoginDbContext db = new LoginDbContext())
           {
               if (db.UserRegisters.Where(a => (a.UserName == model.UserName)).Count() > 0) {

                   return Json(new { result = "error", content = "This user name already exists" });
               }
               if (db.UserRegisters.Where(a => a.UserEmail == model.UserEmail).Count() > 0)
               {
                   return Json(new { result="error", content="Mailbox already exists"});
               }
               db.UserRegisters.Add(model);
               db.SaveChanges();
               return Json(new { result="success",content="Welcome"+model.UserName});
            }
        }

5,CSS3 beautify the page

Here the main use of the CSS3 gradient, drop shadows, text shadow effects

The gradient of CSS code is: -webkit- prefix is to apply the chrome Safari browser, -moz- is available for Firefox, -o- applies to the opera browser, without a prefix to the CSS3 standard.

/*Display this background color does not support CSS3, graceful degradation*/
background:#d2d2d2;
/*The default is perpendicular to the direction of the gradient, the tilt angle from 45 to #d2d2d2 gradient to#ccc*/
background:-webkit-gradient(linear,left top,left bottom,from(#d2d2d2),to(#ccc));
background:-webkit-linear-gradient(-45deg,#d2d2d2,#ccc);
background:-moz-linear-gradient(-45deg,#d2d2d2,#ccc);
background:-o-linear-gradient(-45deg,#d2d2d2,#ccc);
background:linear-gradient(-45deg, #d2d2d2,#ccc);

Drop shadow code for: (note fire, do not use drop shadows very consumption performance)

/*Vertical offset level offset color fuzzy diameter*/
-webkit-box-shadow:8px 5px 15px #404040;
-moz-box-shadow:8px 5px 15px #404040;
box-shadow:8px 5px 15px #404040;

The code for the text shadow:

/*Vertical offset level offset color fuzzy diameter*/
text-shadow:1px 1px 0.5em #fff;

The source code and an example of using CSS3, without the use of a picture, in the manage folder, effect diagram as follows:

ajax jsonpost数据2

Download the source code

ps: Turnover, job hunting...... Guangzhou / Shenzhen   a resume

Use your finger, point your support, your support is my biggest power!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Jeffrey at November 16, 2013 - 3:45 PM