Click here to Skip to main content
Click here to Skip to main content
Articles » Web Development » ASP.NET » Howto » Downloads
 
Add your own
alternative version
Go to top

MVC Techniques with jQuery, JSON, Knockout, and C#

, 2 Jan 2012
Developing an Order Entry application with MVC.
CodeProjectMVC4.zip
ADODataService
ADODataService.csproj.user
bin
Debug
ADODataService.dll
Release
obj
Debug
TempPE
Release
Properties
NorthwindApplicationServices
bin
Debug
ADODataService.dll
NorthwindApplicationServices.dll
NorthwindBusinessServices.dll
NorthwindDataAccessServices.dll
NorthwindDataModel.dll
NorthwindViewModel.dll
Release
NorthwindApplicationServices.csproj.user
obj
Debug
TempPE
Release
Properties
NorthwindBusinessServices
bin
Debug
ADODataService.dll
NorthwindBusinessServices.dll
NorthwindDataAccessServices.dll
NorthwindDataModel.dll
NorthwindViewModel.dll
Release
NorthwindBusinessServices.csproj.user
obj
Debug
TempPE
Release
Properties
NorthwindDataAccessServices
bin
Debug
ADODataService.dll
NorthwindDataAccessServices.dll
NorthwindDataModel.dll
Release
NorthwindDataAccessServices.csproj.user
obj
Debug
TempPE
Release
Properties
NorthwindDataModel
bin
Debug
NorthwindDataModel.dll
Release
NorthwindDataModel.csproj.user
obj
Debug
TempPE
Release
Properties
NorthwindViewModel
bin
Debug
NorthwindDataModel.dll
NorthwindViewModel.dll
Release
NorthwindViewModel.csproj.user
obj
Debug
TempPE
Release
Properties
NorthwindWebApplication
App_Data
bin
ADODataService.dll
EntityFramework.dll
Microsoft.Web.Infrastructure.dll
Microsoft.Web.Optimization.dll
NorthwindApplicationServices.dll
NorthwindBusinessServices.dll
NorthwindDataAccessServices.dll
NorthwindDataModel.dll
NorthwindViewModel.dll
NorthwindWebApplication.dll
NorthwindWebControls.dll
System.Web.Helpers.dll
System.Web.Mvc.dll
System.Web.Providers.dll
System.Web.Razor.dll
System.Web.WebPages.Deployment.dll
System.Web.WebPages.dll
System.Web.WebPages.Razor.dll
Content
Images
DownArrow.gif
icon-calendar.gif
icon-delete.gif
icon-floppy.gif
icon-pencil-x.gif
icon-pencil.gif
Search3.gif
UpArrow.gif
themes
base
images
ui-bg_flat_0_aaaaaa_40x100.png
ui-bg_flat_75_ffffff_40x100.png
ui-bg_glass_55_fbf9ee_1x400.png
ui-bg_glass_65_ffffff_1x400.png
ui-bg_glass_75_dadada_1x400.png
ui-bg_glass_75_e6e6e6_1x400.png
ui-bg_glass_95_fef1ec_1x400.png
ui-bg_highlight-soft_75_cccccc_1x100.png
ui-icons_222222_256x240.png
ui-icons_2e83ff_256x240.png
ui-icons_454545_256x240.png
ui-icons_888888_256x240.png
ui-icons_cd0a0a_256x240.png
Controllers
Global.asax
Helpers
Images
accent.png
aspNetHome.png
bullet.png
facebook.png
findHosting.png
heroAccent.png
NuGetGallery.png
orderedListOne.png
orderedListThree.png
orderedListTwo.png
Search.gif
twitter.png
windowsLive.png
Models
NorthwindWebApplication.csproj.user
obj
Debug
TempPE
Properties
Scripts
Views
Account
Home
Orders
Products
Shared
NorthwindWebControls
bin
Debug
NorthwindWebControls.dll
Release
obj
Debug
TempPE
Properties
packages
AspNetMvc.4.0.10906.0
AspNetMvc.4.0.10906.0.nupkg
lib
net40
System.Web.Mvc.dll
AspNetWebPagesCore.2.0.10906.0
AspNetWebPagesCore.2.0.10906.0.nupkg
lib
net40
System.Web.Helpers.dll
System.Web.Razor.dll
System.Web.WebPages.Deployment.dll
System.Web.WebPages.dll
System.Web.WebPages.Razor.dll
EntityFramework.4.1.10331.0
EntityFramework.4.1.10331.0.nupkg
lib
net40
EntityFramework.dll
jQuery.1.6.2
Content
Scripts
jQuery.1.6.2.nupkg
jQuery.Ajax.Unobtrusive.1.0
Content
Scripts
jQuery.Ajax.Unobtrusive.1.0.nupkg
jQuery.UI.Combined.1.8.11
Content
Content
themes
base
images
ui-bg_flat_0_aaaaaa_40x100.png
ui-bg_flat_75_ffffff_40x100.png
ui-bg_glass_55_fbf9ee_1x400.png
ui-bg_glass_65_ffffff_1x400.png
ui-bg_glass_75_dadada_1x400.png
ui-bg_glass_75_e6e6e6_1x400.png
ui-bg_glass_95_fef1ec_1x400.png
ui-bg_highlight-soft_75_cccccc_1x100.png
ui-icons_222222_256x240.png
ui-icons_2e83ff_256x240.png
ui-icons_454545_256x240.png
ui-icons_888888_256x240.png
ui-icons_cd0a0a_256x240.png
Scripts
jQuery.UI.Combined.1.8.11.nupkg
jQuery.Validation.1.8
Content
Scripts
jQuery.Validation.1.8.nupkg
jQuery.Validation.Unobtrusive.1.0
Content
Scripts
jQuery.Validation.Unobtrusive.1.0.nupkg
knockoutjs.1.2.9.0
Content
Scripts
knockoutjs.1.2.9.0.nupkg
Microsoft.Web.Optimization.0.1
lib
net40
Microsoft.Web.Optimization.dll
Microsoft.Web.Optimization.0.1.nupkg
MicrosoftWebInfrastructure.1.0.0.0
lib
net40
Microsoft.Web.Infrastructure.dll
MicrosoftWebInfrastructure.1.0.0.0.nupkg
Modernizr.2.0.6
Content
Scripts
Modernizr.2.0.6.nupkg
System.Web.Providers.1.0.1
content
web.config.transform
EULA.rtf
lib
Net40
System.Web.Providers.dll
System.Web.Providers.1.0.1.nupkg
SQLScript
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using NorthwindWebApplication.Models;

namespace NorthwindWebApplication.Controllers
{

    [Authorize]
    public class AccountController : Controller
    {

        //
        // GET: /Account/LogOn

        [AllowAnonymous]
        public ActionResult LogOn()
        {
            return ContextDependentView();
        }

        //
        // POST: /Account/JsonLogOn

        [AllowAnonymous]
        [HttpPost]
        public JsonResult JsonLogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    return Json(new { success = true, redirect = returnUrl });
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed
            return Json(new { errors = GetErrorsFromModelState() });
        }

        //
        // POST: /Account/LogOn

        [AllowAnonymous]
        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");
        }

        //
        // GET: /Account/Register

        [AllowAnonymous]
        public ActionResult Register()
        {
            return ContextDependentView();
        }

        //
        // POST: /Account/JsonRegister

        [AllowAnonymous]
        [HttpPost]
        public ActionResult JsonRegister(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
                    return Json(new { success = true });
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed
            return Json(new { errors = GetErrorsFromModelState() });
        }

        //
        // POST: /Account/Register

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {

                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    MembershipUser currentUser = Membership.GetUser(User.Identity.Name, userIsOnline: true);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }

        private ActionResult ContextDependentView()
        {
            string actionName = ControllerContext.RouteData.GetRequiredString("action");
            if (Request.QueryString["content"] != null)
            {
                ViewBag.FormAction = "Json" + actionName;
                return PartialView();
            }
            else
            {
                ViewBag.FormAction = actionName;
                return View();
            }
        }

        private IEnumerable<string> GetErrorsFromModelState()
        {
            return ModelState.SelectMany(x => x.Value.Errors
                .Select(error => error.ErrorMessage));
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Mark J. Caplin
Software Developer Caplin Systems
United States United States
Mark Caplin has specialized in Information Technology solutions for 25 years. Specializing in full life-cycle development projects for both enterprise-wide systems and Internet/Intranet based solutions.
 
For the past ten years or so, Mark has specialized in the Microsoft .NET framework using both C# and VB.NET as his tools of choice.
 
When not coding, Mark enjoys playing tennis, listening to U2 music, watching Miami Dolphins football and watching movies in Blu-Ray technology.
 
In between all this, his wife of over 20 years, feeds him well with some great home cooked meals.
 
...

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 2 Jan 2012
Article Copyright 2011 by Mark J. Caplin
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid