How login.cshtml file work

9 years ago
Hello, I had deploy nopcommerce 2.8 with source code into visual studio 2012. There is one thing that I don't understand in login.cshtml file where login button is being triggered by user. The code is written like this:
<fieldset class="form-fields returning-wrapper">
            <legend>@T("Account.Login.ReturningCustomer")</legend>
            <dl>
                @using (Html.BeginForm())
                {
                    <dd class="message-error">
                        @Html.ValidationSummary(true, T("Account.Login.Unsuccessful").Text)
                    </dd>
                    if (Model.UsernamesEnabled)
                    {
                    <dt>
                        @Html.LabelFor(m => m.Username): </dt>
                    <dd>
                        @Html.TextBoxFor(m => m.Username, new { @class = "username", autofocus = "autofocus" })
                        @Html.ValidationMessageFor(m => m.Username)
                    </dd>
                    }
                    else
                    {
                    <dt>
                        @Html.LabelFor(m => m.Email): </dt>
                    <dd>
                        @Html.TextBoxFor(m => m.Email, new { @class = "email" , autofocus = "autofocus"})
                        @Html.ValidationMessageFor(m => m.Email)
                    </dd>
                    }
                    <dt>
                        @Html.LabelFor(m => m.Password): </dt>
                    <dd>
                        @Html.PasswordFor(m => m.Password, new { @class = "password" })
                        @Html.ValidationMessageFor(m => m.Password)
                    </dd>
                    <dd>
                        @Html.CheckBoxFor(m => m.RememberMe)
                        @Html.LabelFor(m => m.RememberMe)
                    </dd>
                    <dd class="forgot-password">
                        @Html.RouteLink(T("Account.Login.ForgotPassword").Text, "PasswordRecovery")
                    </dd>
                    if (Model.DisplayCaptcha)
                    {
                    <dd class="captcha-box">
                        @Html.Raw(Html.GenerateCaptcha())
                    </dd>
                    }
                    <dd class="buttons">
                        <input class="button-1 login-button" type="submit" value="@T("Account.Login.LoginButton")" />
                    </dd>
                      
                }
            </dl>
        </fieldset>
The button does not even link to other pages but magically it works when I try to login as admin. Can someone please explain to me how this work?
9 years ago
Ok If I read the point right only Registered User Can Login to there account. So when you Install, the Admin user is automatically created.

So when a User is Registered they can login and the button is triggered in the CustomerController. So they can access there Account. I think.
9 years ago
Thanks a lot for your explanation and it really helps me a lot. By the way, i tried to copy the above code and create a login box at the main page but i don't know what to put inside the controller of the login box so i copy the codes from customer controller. But end up having lots of errors and build error too.. So, right now i'm stuck at creating code for that login box controller. And one more thing is that do i need to create any models because now i'm using loginmodel in my codes.
9 years ago
The Logic for the Login Controller Is based in Two Methods.

In 2.8 CustomerController line 377 and 388.

I don't fully understand your requirements further explantion would help. I maybe able to help or someone else would.
9 years ago
This is my loginbox.cshtml file.
@{
    ViewBag.Title = "Login";

}
@model LoginModel
@using Nop.Web.Models.Customer;
@using Nop.Core;
@using Nop.Core.Infrastructure;
@using Nop.Core.Infrastructure.DependencyManagement;
<h2>@ViewBag.Message</h2>
@{
    var registerUrl = Url.RouteUrl("Login");
    if (!String.IsNullOrEmpty(this.Context.Request.QueryString["returnUrl"]))
    {
        var webHelper = EngineContext.Current.Resolve<IWebHelper>();
        registerUrl = webHelper.ModifyQueryString(registerUrl, "returnurl=" + HttpUtility.UrlEncode(this.Context.Request.QueryString["returnUrl"]), null);
    }
}
<div class="block block-loginbox">
    <div class="title">
        <strong>@T("Login")</strong>
    </div>
    <div class="clear">
    </div>
<div class="listbox">
    <fieldset class="form-fields returning-wrapper">
            <legend>@T("Account.Login.ReturningCustomer")</legend>
            <dl>
                @using (Html.BeginForm())
                {
                    <dd class="message-error">
                        @Html.ValidationSummary(true, T("Account.Login.Unsuccessful").Text)
                    </dd>
                    
                    
                    <dt>
                        @Html.LabelFor(m => m.Email): </dt>
                    <dd>
                        @Html.TextBoxFor(m => m.Email, new { @class = "email", autofocus = "autofocus" })
                        @Html.ValidationMessageFor(m => m.Email)
                    </dd>
                    
                    <dt>
                        @Html.LabelFor(m => m.Password): </dt>
                    <dd>
                        @Html.PasswordFor(m => m.Password, new { @class = "password" })
                        @Html.ValidationMessageFor(m => m.Password)
                    </dd>
                    <dd>
                        @Html.CheckBoxFor(m => m.RememberMe)
                        @Html.LabelFor(m => m.RememberMe)
                    </dd>
                    <dd class="forgot-password">
                        @Html.RouteLink(T("Account.Login.ForgotPassword").Text, "PasswordRecovery")
                    </dd>
                  
                    <dd class="buttons">
                        <input class="button-1 login-button" type="submit" onclick="location.href='@registerUrl'" value="@T("Account.Login.LoginButton")" />
                    </dd>
                      
                }
            </dl>
        </fieldset>
        <div class="clear">
        </div>

     </div>
     </div>
And this is my LoginBoxController.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Nop.Web.Models.Customer;
using Nop.Core.Domain.Customers;
using Nop.Web.Models.Customer;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Security;
using Nop.Services.Customers;
using Nop.Services.Localization;
using Nop.Services.Logging;



namespace Nop.Web.Controllers
{
    public class LoginBoxController : Controller
    {
        //
        // GET: /LoginBox/
        [ChildActionOnly]
        public ActionResult Index()
        {
            return View();
        }
        //public ActionResult LoginBox()
        //{
        //    return View();
        //}

        [NopHttpsRequirement(SslRequirement.Yes)]
        public ActionResult Login(bool? checkoutAsGuest)
        {
            var model = new LoginModel();
            model.UsernamesEnabled = _customerSettings.UsernamesEnabled;
            model.CheckoutAsGuest = checkoutAsGuest.HasValue ? checkoutAsGuest.Value : false;
          //  model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage;
            return View(model);
        }
        [HttpPost]
        public ActionResult LoginBox()
        {
            if (ModelState.IsValid)
            {
               if (_customerRegistrationService.ValidateCustomer(_customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password))
                {
                    var customer = _customerSettings.UsernamesEnabled ? _customerService.GetCustomerByUsername(model.Username) : _customerService.GetCustomerByEmail(model.Email);

                    //migrate shopping cart
                    _shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, customer);

                    //sign in new customer
                    _authenticationService.SignIn(customer, model.RememberMe);

                    //activity log
                    _customerActivityService.InsertActivity("PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"), customer);

                    if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                        return Redirect(returnUrl);
                    else
                        return RedirectToRoute("HomePage");
                }
                else
                {
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials"));
                }
            }
        }
}
}
But there are some errors in this controller file like "the name _customerSetting does not exist in the current context",  "the name _customerRegistrationService does not exist in the current context", and same error message for _customerService, _shoppingCartService, _authenticationService, _workContext, _customerActivityService and _localizationService.
9 years ago
I'm still not 100% btw what you are trying to achieve

Look at the feilds and ctor that are being injected into the customer controller. Add the required feilds

Eg

private readonly IAuthenticationService _authenticationService;
public CustomerController(IAuthenticationService authenticationService, etc


But I presume

If you are trying to block unregistered user from the site before registering reference the following forum post please

https://www.nopcommerce.com/boards/t/22546/wholesale-website-user-to-be-logged-in-to-view-website-how-to-setup.aspx

Point two.
9 years ago
annachoi wrote:
This is my loginbox.cshtml file.
@{
    ViewBag.Title = "Login";

}
@model LoginModel
@using Nop.Web.Models.Customer;
@using Nop.Core;
@using Nop.Core.Infrastructure;
@using Nop.Core.Infrastructure.DependencyManagement;
<h2>@ViewBag.Message</h2>
@{
    var registerUrl = Url.RouteUrl("Login");
    if (!String.IsNullOrEmpty(this.Context.Request.QueryString["returnUrl"]))
    {
        var webHelper = EngineContext.Current.Resolve<IWebHelper>();
        registerUrl = webHelper.ModifyQueryString(registerUrl, "returnurl=" + HttpUtility.UrlEncode(this.Context.Request.QueryString["returnUrl"]), null);
    }
}
<div class="block block-loginbox">
    <div class="title">
        <strong>@T("Login")</strong>
    </div>
    <div class="clear">
    </div>
<div class="listbox">
    <fieldset class="form-fields returning-wrapper">
            <legend>@T("Account.Login.ReturningCustomer")</legend>
            <dl>
                @using (Html.BeginForm())
                {
                    <dd class="message-error">
                        @Html.ValidationSummary(true, T("Account.Login.Unsuccessful").Text)
                    </dd>
                    
                    
                    <dt>
                        @Html.LabelFor(m => m.Email): </dt>
                    <dd>
                        @Html.TextBoxFor(m => m.Email, new { @class = "email", autofocus = "autofocus" })
                        @Html.ValidationMessageFor(m => m.Email)
                    </dd>
                    
                    <dt>
                        @Html.LabelFor(m => m.Password): </dt>
                    <dd>
                        @Html.PasswordFor(m => m.Password, new { @class = "password" })
                        @Html.ValidationMessageFor(m => m.Password)
                    </dd>
                    <dd>
                        @Html.CheckBoxFor(m => m.RememberMe)
                        @Html.LabelFor(m => m.RememberMe)
                    </dd>
                    <dd class="forgot-password">
                        @Html.RouteLink(T("Account.Login.ForgotPassword").Text, "PasswordRecovery")
                    </dd>
                  
                    <dd class="buttons">
                        <input class="button-1 login-button" type="submit" onclick="location.href='@registerUrl'" value="@T("Account.Login.LoginButton")" />
                    </dd>
                      
                }
            </dl>
        </fieldset>
        <div class="clear">
        </div>

     </div>
     </div>
And this is my LoginBoxController.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Nop.Web.Models.Customer;
using Nop.Core.Domain.Customers;
using Nop.Web.Models.Customer;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Security;
using Nop.Services.Customers;
using Nop.Services.Localization;
using Nop.Services.Logging;



namespace Nop.Web.Controllers
{
    public class LoginBoxController : Controller
    {
        //
        // GET: /LoginBox/
        [ChildActionOnly]
        public ActionResult Index()
        {
            return View();
        }
        //public ActionResult LoginBox()
        //{
        //    return View();
        //}

        [NopHttpsRequirement(SslRequirement.Yes)]
        public ActionResult Login(bool? checkoutAsGuest)
        {
            var model = new LoginModel();
            model.UsernamesEnabled = _customerSettings.UsernamesEnabled;
            model.CheckoutAsGuest = checkoutAsGuest.HasValue ? checkoutAsGuest.Value : false;
          //  model.DisplayCaptcha = _captchaSettings.Enabled && _captchaSettings.ShowOnLoginPage;
            return View(model);
        }
        [HttpPost]
        public ActionResult LoginBox()
        {
            if (ModelState.IsValid)
            {
               if (_customerRegistrationService.ValidateCustomer(_customerSettings.UsernamesEnabled ? model.Username : model.Email, model.Password))
                {
                    var customer = _customerSettings.UsernamesEnabled ? _customerService.GetCustomerByUsername(model.Username) : _customerService.GetCustomerByEmail(model.Email);

                    //migrate shopping cart
                    _shoppingCartService.MigrateShoppingCart(_workContext.CurrentCustomer, customer);

                    //sign in new customer
                    _authenticationService.SignIn(customer, model.RememberMe);

                    //activity log
                    _customerActivityService.InsertActivity("PublicStore.Login", _localizationService.GetResource("ActivityLog.PublicStore.Login"), customer);

                    if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                        return Redirect(returnUrl);
                    else
                        return RedirectToRoute("HomePage");
                }
                else
                {
                    ModelState.AddModelError("", _localizationService.GetResource("Account.Login.WrongCredentials"));
                }
            }
        }
}
}
But there are some errors in this controller file like "the name _customerSetting does not exist in the current context",  "the name _customerRegistrationService does not exist in the current context", and same error message for _customerService, _shoppingCartService, _authenticationService, _workContext, _customerActivityService and _localizationService.


Hi Anna,

My understanding is that you want to duplicate the login box on the home page. If you want to do this, you don't really need to create a new controller. All you need to do is to:

1. Copy the relevant code of Login.cshtml into another view, let say _LoginBox.cshtml.

2. In the new _LoginBox.cshtml, change the 'Html.BeginForm' part to point to the correct URL:
Html.BeginForm("Login", "Customer")


3. Call the partial view from Index.cshtml:

@Html.Partial("_LoginBox", new Nop.Web.Models.Customer.LoginModel())


This should do the trick. :D
9 years ago
Hello Wooncherk, thanks for help.. yups yups, you are right.. i want to duplicate login box into home page under newsletter box. so for creating _LoginBox, do i need to select create as a partial view or no need to select? I'm so sorry because I'm very new to this.
9 years ago
annachoi wrote:
Hello Wooncherk, thanks for help.. yups yups, you are right.. i want to duplicate login box into home page under newsletter box. so for creating _LoginBox, do i need to select create as a partial view or no need to select? I'm so sorry because I'm very new to this.


It actually doesn't matter. Haha. They are both .cshtml. :D
9 years ago
Oh, i see.. I did what you had told me earlier, create another _LoginBox.cshtml in Views\Customer folder and found out index.cshtml is using _ColumnsThree.cshtml. So, i tried to add this into _ColumnsThree.cshtml.
@Html.Partial("_LoginBox", new Nop.Web.Models.Customer.LoginModel())

And I received this error stated InvalidOperationException was unhandled by user code.
The partial view '_LoginBox' was not found or no view engine supports the searched locations. The following locations were searched:

~/Themes/DefaultClean/Views/Home/_LoginBox.cshtml

~/Themes/DefaultClean/Views/Home/_LoginBox.vbhtml

~/Themes/DefaultClean/Views/Shared/_LoginBox.cshtml

~/Themes/DefaultClean/Views/Shared/_LoginBox.vbhtml

~/Views/Home/_LoginBox.cshtml

~/Views/Home/_LoginBox.vbhtml

~/Views/Shared/_LoginBox.cshtml

~/Views/Shared/_LoginBox.vbhtml

~/Administration/Views/Home/_LoginBox.cshtml

~/Administration/Views/Home/_LoginBox.vbhtml

~/Administration/Views/Shared/_LoginBox.cshtml

~/Administration/Views/Shared/_LoginBox.vbhtml