DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Dynamic Web Forms In React For Enterprise Platforms
  • How to Get Word Document Form Values Using Java
  • Lightning Data Service for Lightning Web Components

Trending

  • Strategies for Securing E-Commerce Applications
  • Designing AI Multi-Agent Systems in Java
  • Data Lake vs. Warehouse vs. Lakehouse vs. Mart: Choosing the Right Architecture for Your Business
  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 1

Override Action Method Using Plugin into nopCommerce3.8

Take a look at this simple tutorial that demonstrates how to override the action method in nopCommerce 3.8.

By 
sangeet shah user avatar
sangeet shah
·
Mar. 16, 20 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
10.0K Views

Join the DZone community and get the full member experience.

Join For Free

This article shows you how to override the action method in nopCommerce 3.8 version. In this article, I am going to override the Contact us form to extend its functionality. But this action method override way is not worked over seo URL (route value) like product URL, category URL, etc.

Override Contact Us page

Now, I am going to show how to override the Contact us page using plugin. This Contact us form has fields like name, emailid, and content, but I want to add one more field, contact no, that will help me to get the contact details of the person who is going to post this form.


You may also enjoy: A Beginner's Guide to Overriding Methods


For this feature, I am going to add one project into the plugin folder and add the ContactusController.cs, RouteProvider.cs, ContactUsModel.cs, ContactUs.cshtml, app.config, description.txt, OverrideActionMethodProvider.cs, packages.config, and web.config. For now, I refer to the Nop.Plugin.ExternalAuth.Facebook plugin.

My plugin structure is as below:

Plugin structure

I have created:

  • ContactSscontroller.cs => for the Contact us form get or post method.
  • RouteProvider.cs => is used to override the route URL of Contact us. If the user calls the Contact us URL, then our plugin form will be displayed instead of default nopCommerce form (action method).
  • ContactUsmodel.cs => to add one more property of contact no.
  • ContactUs.cshtml => This view file displays content of Contact us form.
  • OverrideActionMethodProvider.cs => creating a method for the install and uninstall process for plugin

ContactUsmodel.cs model file. I have added my new property into this model. I have used the existing ContactUsModel of nopCommerce.

C#
 




xxxxxxxxxx
1
10


 
1
  1  using Nop.Web.Framework;
2
  2  
3
  3  namespace Nop.Plugin.OverrideActionMethod.Models
4
  4  {
5
  5      public class ContactUsModel : Nop.Web.Models.Common.ContactUsModel
6
  6      {
7
  7          [NopResourceDisplayName("Account.Fields.Phone")]
8
  8          public string PhoneNo { get; set; }
9
  9      }
10
 10  }


RouteProvider.cs routeProvider file overrides the existing route value:

C#
 




x
19


 
1
  1  using Nop.Web.Framework.Localization;  
2
  2     using Nop.Web.Framework.Mvc.Routes;  
3
  3     using System.Web.Routing;  
4
  4     using System.Linq;  
5
  5       
6
  6     namespace Nop.Web.Infrastructure  
7
  7     {  
8
  8         public partial class RouteProvider : IRouteProvider  
9
  9         {  
10
 10             public void RegisterRoutes(RouteCollection routes)  
11
 11             {  
12
 12                 routes.Remove(routes.FirstOrDefault(c => (c as Route).Url == "contactus"));  
13
 13                 routes.MapLocalizedRoute("ContactUs",  
14
 14                                  "contactus",  
15
 15                                  new { controller = "ContactUs", action = "ContactUs" },  
16
 16                                  new[] { "Nop.Plugin.OverrideActionMethod.Controllers" });  
17
 17             }    
18
 18         }  
19
 19     }  


I have removed the existing route value of Contact us and added my Contact us route value. I have mentioned my controller name, action method name, and namespace for this.

Contactus.cshtml view file:

C#
 




xxxxxxxxxx
1
99


 
1
  1  @model ContactUsModel
2
  2  @using Nop.Plugin.OverrideActionMethod.Models
3
  3  @using Nop.Web.Framework
4
  4  @using Nop.Web.Framework.UI
5
  5  @using Nop.Web.Framework.Security.Captcha
6
  6  @{
7
  7      Layout = "~/Views/Shared/_ColumnsOne.cshtml";
8
  8  
9
  9      //title
10
 10      Html.AddTitleParts(T("PageTitle.ContactUs").Text);
11
 11      //page class
12
 12      Html.AppendPageCssClassParts("html-contact-page");
13
 13  }
14
 14  <div class="page contact-page">
15
 15      <div class="page-title">
16
 16          <h1>@T("PageTitle.ContactUs")</h1>
17
 17      </div>
18
 18      <div class="page-body">
19
 19          @Html.Action("TopicBlock",
20
 20          "Topic", new { systemName = "ContactUs" })
21
 21          @Html.Widget("contactus_top")
22
 22          @if (Model.SuccessfullySent)
23
 23          {
24
 24              <div class="result">
25
 25                  @Model.Result
26
 26              </div>
27
 27          }
28
 28          else
29
 29          {
30
 30              using (Html.BeginForm("ContactUsSend",
31
 31              "ContactUs", FormMethod.Post, new { id = "form" }))
32
 32              {
33
 33                  @Html.AntiForgeryToken()
34
 34                  var validationSummary = Html.ValidationSummary(true);
35
 35                  if (!MvcHtmlString.IsNullOrEmpty(validationSummary))
36
 36                  {
37
 37                      <div class="message-error">@validationSummary</div>
38
 38                  }
39
 39                  <div class="fieldset">
40
 40                      <div class="form-fields">
41
 41                          <div class="inputs">
42
 42                              @Html.LabelFor(model => model.FullName)
43
 43                              @Html.TextBoxFor(model => model.FullName,
44
 44                              new { @class = "fullname",
45
 45                              placeholder = T("ContactUs.FullName.Hint") })
46
 46                              @Html.RequiredHint()
47
 47                              @Html.ValidationMessageFor(model => model.FullName)
48
 48                          </div>
49
 49                          <div class="inputs">
50
 50                              @Html.LabelFor(model => model.Email)
51
 51                              @Html.TextBoxFor(model => model.Email,
52
 52                              new { @class = "email",
53
 53                              placeholder = T("ContactUs.Email.Hint") })
54
 54                              @Html.RequiredHint()
55
 55                              @Html.ValidationMessageFor(model => model.Email)
56
 56                          </div>
57
 57                          @if (Model.SubjectEnabled)
58
 58                          {
59
 59                              <div class="inputs">
60
 60                                  @Html.LabelFor(model => model.Subject)
61
 61                                  @Html.TextBoxFor(model => model.Subject,
62
 62                                  new { @class = "subject",
63
 63                                  placeholder = T("ContactUs.Subject.Hint") })
64
 64                                  @Html.RequiredHint()
65
 65                                  @Html.ValidationMessageFor(model => model.Subject)
66
 66                              </div>
67
 67                          }
68
 68                          <div class="inputs">
69
 69                              @Html.LabelFor(model => model.Enquiry)
70
 70                              @Html.TextAreaFor(model => model.Enquiry,
71
 71                              new { @class = "enquiry",
72
 72                              placeholder = T("ContactUs.Enquiry.Hint") })
73
 73                              @Html.RequiredHint()
74
 74                              @Html.ValidationMessageFor(model => model.Enquiry)
75
 75                          </div>
76
 76                          @if (Model.DisplayCaptcha)
77
 77                          {
78
 78                              <div class="captcha-box">
79
 79                                  @Html.Raw(Html.GenerateCaptcha())
80
 80                              </div>
81
 81                          }
82
 82  
83
 83                          <div class="inputs">  
84
 84                              @Html.LabelFor(model => model.PhoneNo)  
85
 85                              @Html.TextBoxFor(model => model.PhoneNo)  
86
 86                              @Html.ValidationMessageFor(model => model.PhoneNo)  
87
 87                          </div>  
88
 88                      </div>
89
 89                  </div>
90
 90                  <div class="buttons">
91
 91                      <input type="submit" name="send-email"
92
 92                      class="button-1 contact-us-button"
93
 93                      value="@T("ContactUs.Button")" />
94
 94                  </div>
95
 95              }
96
 96          }
97
 97          @Html.Widget("contactus_bottom")
98
 98      </div>
99
 99  </div>


I have only added phone no text into this view file and changed the form post action method name to post into my controller.

ContactUsController.cs

C#
 




xxxxxxxxxx
1
161


 
1
  1  using Nop.Core;
2
  2  using Nop.Core.Domain.Common;
3
  3  using Nop.Core.Domain.Messages;
4
  4  using Nop.Plugin.OverrideActionMethod.Models;
5
  5  using Nop.Services.Customers;
6
  6  using Nop.Services.Localization;
7
  7  using Nop.Services.Logging;
8
  8  using Nop.Services.Messages;
9
  9  using Nop.Web.Controllers;
10
 10  using Nop.Web.Framework.Security;
11
 11  using Nop.Web.Framework.Security.Captcha;
12
 12  using System;
13
 13  using System.Linq;
14
 14  using System.Web.Mvc;
15
 15  
16
 16  namespace Nop.Plugin.OverrideActionMethod.Controllers
17
 17  {
18
 18      public class ContactUsController : BasePublicController
19
 19      {
20
 20          #region Fields
21
 21  
22
 22          private readonly ILocalizationService _localizationService;
23
 23          private readonly IWorkContext _workContext;
24
 24          private readonly IStoreContext _storeContext;
25
 25          private readonly IQueuedEmailService _queuedEmailService;
26
 26          private readonly IEmailAccountService _emailAccountService;
27
 27          private readonly ICustomerActivityService _customerActivityService;
28
 28          private readonly EmailAccountSettings _emailAccountSettings;
29
 29          private readonly CommonSettings _commonSettings;
30
 30          private readonly CaptchaSettings _captchaSettings;
31
 31  
32
 32          #endregion
33
 33  
34
 34          #region Constructors
35
 35  
36
 36          public ContactUsController(
37
 37              ILocalizationService localizationService,
38
 38              IWorkContext workContext,
39
 39              IStoreContext storeContext,
40
 40              IQueuedEmailService queuedEmailService,
41
 41              IEmailAccountService emailAccountService,
42
 42              ICustomerActivityService customerActivityService,
43
 43              EmailAccountSettings emailAccountSettings,
44
 44              CommonSettings commonSettings,
45
 45              CaptchaSettings captchaSettings)
46
 46          {
47
 47              this._localizationService = localizationService;
48
 48              this._workContext = workContext;
49
 49              this._storeContext = storeContext;
50
 50              this._queuedEmailService = queuedEmailService;
51
 51              this._emailAccountService = emailAccountService;
52
 52              this._customerActivityService = customerActivityService;
53
 53              this._emailAccountSettings = emailAccountSettings;
54
 54              this._commonSettings = commonSettings;
55
 55              this._captchaSettings = captchaSettings;
56
 56          }
57
 57  
58
 58          #endregion
59
 59  
60
 60          #region Methods
61
 61  
62
 62          public ActionResult ContactUs()
63
 63          {
64
 64              var model = new ContactUsModel
65
 65              {
66
 66                  Email = _workContext.CurrentCustomer.Email,
67
 67                  FullName = _workContext.CurrentCustomer.GetFullName(),
68
 68                  SubjectEnabled = _commonSettings.SubjectFieldOnContactUsForm,
69
 69                  DisplayCaptcha = _captchaSettings.Enabled &&
70
 70                  _captchaSettings.ShowOnContactUsPage
71
 71              };
72
 72              return View("~/Plugins/Plugin.OverrideActionMethod/Views/ContactUs/
73
 73                                ContactUs.cshtml", model);
74
 74          }
75
 75  
76
 76          [HttpPost]
77
 77          [PublicAntiForgery]
78
 78          [CaptchaValidator]
79
 79          public ActionResult ContactUsSend(ContactUsModel model, bool captchaValid)
80
 80          {
81
 81              //validate CAPTCHA
82
 82              if (_captchaSettings.Enabled &&
83
 83              _captchaSettings.ShowOnContactUsPage && !captchaValid)
84
 84              {
85
 85                  ModelState.AddModelError
86
 86                  ("", _captchaSettings.GetWrongCaptchaMessage(_localizationService));
87
 87              }
88
 88  
89
 89              if (ModelState.IsValid)
90
 90              {
91
 91                  var phoneNo = model.PhoneNo;
92
 92                  string email = model.Email.Trim();
93
 93                  string fullName = model.FullName;
94
 94                  string subject = _commonSettings.SubjectFieldOnContactUsForm ?
95
 95                      model.Subject :
96
 96                      string.Format(_localizationService.GetResource
97
 97                      ("ContactUs.EmailSubject"),
98
 98                      _storeContext.CurrentStore.GetLocalized(x => x.Name));
99
 99  
100
100                  var emailAccount = _emailAccountService.GetEmailAccountById
101
101                  (_emailAccountSettings.DefaultEmailAccountId);
102
102                  if (emailAccount == null)
103
103                      emailAccount =
104
104                         _emailAccountService.GetAllEmailAccounts().FirstOrDefault();
105
105                  if (emailAccount == null)
106
106                      throw new Exception("No email account could be loaded");
107
107  
108
108                  string from;
109
109                  string fromName;
110
110                  string body = Core.Html.HtmlHelper.FormatText
111
111                  (model.Enquiry, false, true, false, false, false, false);
112
112                  //required for some SMTP servers
113
113                  if (_commonSettings.UseSystemEmailForContactUsForm)
114
114                  {
115
115                      from = emailAccount.Email;
116
116                      fromName = emailAccount.DisplayName;
117
117                      body = string.Format("<strong>From</strong>:
118
118                      {0} - {1}<br /><br />{2}",
119
119                          Server.HtmlEncode(fullName),
120
120                          Server.HtmlEncode(email), body);
121
121                  }
122
122                  else
123
123                  {
124
124                      from = email;
125
125                      fromName = fullName;
126
126                  }
127
127                  _queuedEmailService.InsertQueuedEmail(new QueuedEmail
128
128                  {
129
129                      From = from,
130
130                      FromName = fromName,
131
131                      To = emailAccount.Email,
132
132                      ToName = emailAccount.DisplayName,
133
133                      ReplyTo = email,
134
134                      ReplyToName = fullName,
135
135                      Priority = QueuedEmailPriority.High,
136
136                      Subject = subject,
137
137                      Body = body,
138
138                      CreatedOnUtc = DateTime.UtcNow,
139
139                      EmailAccountId = emailAccount.Id,
140
140                  });
141
141  
142
142                  model.SuccessfullySent = true;
143
143                  model.Result = _localizationService.GetResource
144
144                                 ("ContactUs.YourEnquiryHasBeenSent");
145
145  
146
146                  //activity log
147
147                  _customerActivityService.InsertActivity("PublicStore.ContactUs",
148
148                  _localizationService.GetResource("ActivityLog.PublicStore.ContactUs"));
149
149  
150
150                  return View("~/Plugins/Plugin.OverrideActionMethod/
151
151                               Views/ContactUs/ContactUs.cshtml", model);
152
152              }
153
153  
154
154              model.DisplayCaptcha = _captchaSettings.Enabled &&
155
155                                     _captchaSettings.ShowOnContactUsPage;
156
156              return View("~/Plugins/Plugin.OverrideActionMethod/Views/ContactUs/
157
157                            ContactUs.cshtml", model);
158
158          }
159
159          #endregion
160
160      }
161
161  }


This controller helps me to display my Contact us form and get the form detail into my end to get new property value.

I hope you've now understood how to override the action method using plugin in nopcommerce3.8. I have attached the source code of this plugin so you will be able to get a better idea about this.

Download project source code here.

Contacts (Apple) Form (document)

Published at DZone with permission of sangeet shah. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Dynamic Web Forms In React For Enterprise Platforms
  • How to Get Word Document Form Values Using Java
  • Lightning Data Service for Lightning Web Components

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!