RSpec can not find modal in React/Rails view - ruby-on-rails

I have a modal in my Rails app that appears when you click on a button called "New Post." You can then fill out a form and it will create a post. This is all handled with React (if that matters). RSpec is unable to find any element within the modal. Here is my test:
require 'rails_helper'
RSpec.feature "Creating a post" do
before do
#user = User.create(email:"email#gmail.com", password: "password")
end
scenario "A valid user creates a post" do
visit '/'
click_link 'Login'
fill_in "Email", with: "email#gmail.com"
fill_in "Password", with: "password"
click_button "Log in"
click_link "New Post"
expect(page).to have_content("Create a Post")
end
end
Here is the error this test throws:
expected to find text "Create a Post" in "Toggle navigation ReactBlog Home Logout New Post
I tried adding sleeps to see if the animation in the toggle was doing it, but nothing happened. Here is the full React class that contains the modal. Any thoughts would be helpful.
var Posts = React.createClass({
getInitialState: function(){
return {
posts: this.props.posts,
post: {
title: '',
author: '',
content: '',
video: ''
}
}
},
handlePostCreate: function(){
var that = this;
$.ajax({
method: 'POST',
data: { post: that.state.post },
url: '/posts.json',
success: function(res){
var newPostList = that.state.posts;
newPostList.push(res);
that.setState({
posts: newPostList,
post: {
title: '',
author: '',
content: '',
video: ''
}
});
}
});
},
handlePostDelete(post){
var postList = this.state.posts.filter(function(item) {
return post.id !== item.id;
});
this.setState({posts: postList});
},
handleTitleChange(e) {
var newPost = this.state.post
newPost.title = e.target.value
this.setState({post: newPost});
},
handleAuthorChange(e) {
var newPost = this.state.post
newPost.author = e.target.value
this.setState({post: newPost});
},
handleContentChange(e) {
var newPost = this.state.post
newPost.content = e.target.value
this.setState({post: newPost});
},
handleVideoChange(e) {
var newPost = this.state.post
newPost.video = e.target.value
this.setState({ post: newPost });
},
render: function(){
var that = this;
var postBoard = this.state.posts.map(function(post){
return (
<Post post={post} key={post.id} onDeletePost={that.handlePostDelete} />
);
});
return (
<div>
<div className="modal fade" id="myModal" role="dialog">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal">×</button>
<h4 className="modal-title">Create a Post</h4>
</div>
<div className="modal-body">
<div className='form-group'>
<input value={this.state.post.title} onChange={this.handleTitleChange} type='text' id="Title" className='form-control' placeholder="Title" />
</div>
<div className='form-group'>
<input value={this.state.post.author} onChange={this.handleAuthorChange} type='text' className='form-control' placeholder="Author" />
</div>
<div className='form-group'>
<input value={this.state.post.video} onChange={this.handleVideoChange} type="text" className='form-control' placeholder="Video URL" />
</div>
<div className='form-group'>
<textarea value={this.state.post.content} onChange={this.handleContentChange} type="text" className="form-control" placeholder="Content" ></textarea>
</div>
</div>
<div className="modal-footer">
<button type="button" onClick={this.handlePostCreate} className="btn btn-primary" data-dismiss="modal">Post</button>
</div>
</div>
</div>
</div>
{ postBoard }
</div>
);
}
});

You have to enable javascript for the test.
scenario "A valid user creates a post", js: true do
...
end
Also, try adding save_and_open_page to see if you're getting what's expected
scenario "A valid user creates a post", js: true do
...
save_and_open_page
end

Related

Autocomplete in a modal is not listed/populated

I am creating an 'assign button' which calls a modal. In this modal will search a username queried from a database table. This autocomplete should be listed in the modal box, in fact it is not. I am using Jquery UI for this.
The "No search result" text is behind the modal, as well the assignee is listed behind the modal.
I am detailing my code in this jsfiddle
This is my original code:
$("#user_name").autocomplete({
source: function(request, response) {
$.ajax({
url: "https://dummyjson.com/products",
// url: "<?= site_url('Inventory/readuser'); ?>",
method: "get",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
console.log("response --> ", data);
response(data); //callback fn
}
}) //ajax
console.log("ok");
}, //source
select: function(event, ui) {
$('[name="username"]').val(ui.item.username);
$('[name="role"]').val(ui.item.role);
$('[name="location"]').val(ui.item.location);
}
}); //#user_name
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-3">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js" integrity="sha512-57oZ/vW8ANMjR/KQ6Be9v/+/h6bq9/l3f0Oc7vn6qMqyhvPd1cvKBRWWpzu0QoneImqr2SkmO4MSqU+RpHom3Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<i class="bx bxs-filter-alt text-white-50"></i>Assign
</div>
<div class="modal fade" id="updateUser" tabindex="-1" aria-labelledby="updateUser" aria-hidden="true">
<div class="modal-dialog modal-dialog-sm modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Assign user ...</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<fieldset class="border rounded-3 p-2">
<legend class="float-none w-auto px-2 small">type a user name</legend>
<div class="frmSearch">
<input type="text" class="form-control form-control-sm" id="user_name" name="user_name" size="20" maxlength="3">
<div id="suggesstion-box"></div>
</div>
</fieldset>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-save-filter" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary btn-save-filter" data-bs-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
but in fiddle I am using dummy json from
https://dummyjson.com/docs/products
Please advise how to put the listed value into the green box in the modal.
Please review the following:
https://jsfiddle.net/Twisty/orv2j67n/1/
JavaScript
$("#user_name").autocomplete({
appendTo: "#suggestion-box",
source: function(request, response) {
$.ajax({
url: "https://dummyjson.com/products",
method: "get",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
var results = $.map(data.products, function(v, i) {
v = $.extend(v, {
label: v.brand,
value: v.brand
});
return v;
});
console.log(results);
response(results);
}
});
console.log("ok");
},
select: function(event, ui) {
$('[name="label"]').val(ui.item.title);
}
});
Two changes to be aware of:
appendTo: "#suggestion-box",
Which element the menu should be appended to. When the value is null, the parents of the input field will be checked for a class of ui-front. If an element with the ui-front class is found, the menu will be appended to that element. Regardless of the value, if no element is found, the menu will be appended to the body.
I also added a $.map() in the Success. This ensure that the proper elements exist when passing the data back to response().
var results = $.map(data.products, function(v, i) {
v = $.extend(v, {
label: v.brand,
value: v.brand
});
return v;
});
console.log(results);
response(results);
This is discussed here: https://api.jqueryui.com/autocomplete/#option-source
An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

Server Error in '/' Application in .net mvc

I am working with ASP.NET MVC .
I give the proper url name but error is the resource is not found.
I am click the checkout button and trying to open view but view is not open.
Please see below code.
cartDisplay.cshtml
#{
ViewBag.Title = "cartDisplay";
}
<h2>Add to Cart Details</h2>
<script src="~/kendo/js/kendo.all.min.js"></script>
<div style="display: inline">
<div class="text-left">
<button class='btn btn-group-sm btn-success' onclick='submit()'>CheckOut</button>
</div>
</div>
<div id="example">
<br />
<br />
<div id="grid"></div>
<script>
$(document).ready(function () {
//here other code
function submit() {
debugger
$.ajax({
url: "/User/addToCartOrderStore", //here I am giving the proper url but error is resource not found error
type: 'GET',
cache: false,
contentType: false,
processData: false,
success: function (response) {
window.location.href = response.redirectToUrl;
}
});
}
</script>
UserController.cs
//Shipping Details and order details
[HttpGet]
public ActionResult addToCartOrderStore()
{
return View();
}
[HttpPost]
public ActionResult addToCartOrderStore(FormCollection sh)
{
....
}
I am trying to open below view but below view is not open
addToCartOrderStore.cshtml:
#{
ViewBag.Title = "addToCartOrderStore";
}
<h2>AddToCart OrderStore</h2>
<script src="~/kendo/js/kendo.all.min.js"></script>
<br />
<div class="navbar navbar-inverse text-center">
<div class="container text-center">
<div class="navbar-collapse collapse text-center">
<ul class="nav navbar-nav text-center">
#*<li>#Html.ActionLink("Home", "index")</li>
<li> #Html.ActionLink("My Cart", "cartdisplay")</li>
<li> #Html.ActionLink("My Orders", "orderdisplay")</li>*#
<li>#Html.ActionLink("Logout", "Logout")</li>
</ul>
</div>
</div>
</div>
<form id="form"></form>
<script>
$(document).ready(function () {
var today = new Date();
var maxDate = today.setDate(today.getDate() + 60);
$("#form").kendoForm({
layout: "grid",
grid: {
cols: 2,
gutter: 20
},
items: [
{
type: "group",
label: "Customer Address",
items: [
{
field: "firstname",
label: "First Name:",
validation: { required: true }
},
{
field: "lastname",
label: "Last Name:",
validation: { required: true }
},
See below error image:
I am trying to open view but give an error the resource cannot be found.
I trying to return view but give an error but view is not shown.
need help

Viewbag content does not appear

I have an APS.Net web app Razor view where I attempt to display the Viewbag.errormessage.
The action method populates the viewbag but the view does not show the error message that is in the viewbag. It does not appear. Why?
The paragraph to which the Viewbag is attached to does not even appear per the 2nd pic. In the 1st pic, I can see that is there.
I also tried using 'TempData' but it produces the same result - not appearing.
Here is the action method (simplified):
[HttpPost]
public async Task<ActionResult> DeleteUserAccount(string userName, string
password)
{
try
{
if (string.IsNullOrEmpty(userName) ||
string.IsNullOrEmpty(password))
{
ViewBag.errormessage = "The 'user name' or 'password' is
invalid - empty. Please try again.";
}
else
{
// Cast.
if ((string)Session["UserName"] == userName)
{
}
else
{
ViewBag.errormessage = "Your 'user name' is invalid. It
is not the same as the 'user name' used at original sign
in. Please try again.";
}
}
}
catch (Exception ex1)
{
}
return View();
}
Here is the view:
#Html.AntiForgeryToken()
<div class="login-panel">
#if (ViewBag.errormessage != null)
{
<p class="alert alert-danger" id="errorMessage">#ViewBag.errormessage</p>
}
<div class="form-group">
<div class="col-md-12 col-xs-12">
<h2>Delete Account</h2>
<br />
<h4 class="verify"><strong>I will need to verify your identity in order to delete your account.</strong></h4>
<br />
<h4 class="verify"><strong>Please provide the following:</strong></h4>
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="UserName">User Name</label>
<input id="UserName" type="text" value="" name="UserName">
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="Password">Password</label>
<input id="Password" type="text" value="" name="Password">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<br />
<input class="btn btn-primary deleteUserAccount" value="Delete Account">
#Html.ActionLink("Cancel", "Index", "User", null, new { #class = "btn btn-info" })
</div>
</div>
</div>
<div class="modal fade" id="myModal4" role="dialog" display="none">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" style="padding:10px;">
<h4 class="text-center">Are you sure you want to permanently delete your account and all it contains? Continue ?</h4>
<div class="text-center">
<a class="btn btn-info btn-yes4">Yes</a>
<a class="btn btn-default btn-no4">No</a>
</div>
</div>
</div>
</div>
</div>
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#Styles.Render("~/Content/css")
<script type="text/javascript">
$(document).ready(function () {
$(".deleteUserAccount").click(function (e) {
var holdUserName = $('#UserName').val();
var holdPassword = $('#Password').val();
$("#myModal4").modal({
backdrop: 'static',
keyboard: false
});
$(".btn-yes4").click(function () {
$("#myModal4").modal("hide");
// Do the delete.
// - Pass the 2 fields.
$.ajax({
type: 'POST',
url: '#Url.Action("DeleteUserAccount", "User")',
data: { userName: holdUserName, password: holdPassword},
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
error: function (xhr, ajaxOptions, thrownError) {
alert('Critical Error: something is wrong in the call to DeleteUserAccount for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
}
});
// Return.
return true;
});
$(".btn-no4").click(function () {
$("#myModal4").modal("hide");
return false;
});
$("#myModal4").on('hidden.bs.modal', function () {
$("#myModal4").remove();
});
});
})
</script>
https://dotnetfiddle.net/U6HGHD
Ajax makes a call and does not re-render a page
Controller
[HttpPost]
//I made method snchronous as it has no await, and there are no resources to add await to
public ActionResult DeleteUserAccount(string userName, string password)
{
var errorMessage = String.Empty;
try
{
if (string.IsNullOrEmpty(userName) ||
string.IsNullOrEmpty(password))
{
//since this method is ajax, the view will not re-render, so errors need
//to go into return value.
//ViewBag.errormessage = "The 'user name' or 'password' is invalid - empty.Please try again.";
errorMessage = "The 'user name' or 'password' is invalid - empty.Please try again.";
}
else
{
// Cast.
if ((string)Session["UserName"] == userName)
{
}
else
{
//ViewBag.errormessage = "Your 'user name' is invalid. It is not the same as the 'user name' used at original sign in. Please try again.";
errorMessage = "Your 'user name' is invalid. It is not the same as the 'user name' used at original sign in. Please try again.";
}
}
}
catch (Exception ex1){}
//return View();
//since this is ajax, I am returning a json
return Json(errorMessage, JsonRequestBehavior.AllowGet);
}
public ActionResult Index19()
{
return View();
}
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index19</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js" integrity="sha384-LtrjvnR4Twt/qOuYxE721u19sVFLVSA4hf/rRt6PrZTmiPltdZcI7q7PXQBYTKyf" crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".deleteUserAccount").click(function (e) {
//put this in here
$("#myModal4").modal({
backdrop: 'static',
keyboard: false
});
//fixed the following line
});
$(".btn-yes4").click(function () {
//put these here
var holdUserName = $('#UserName').val();
var holdPassword = $('#Password').val();
$("#myModal4").modal("hide");
// Do the delete.
// - Pass the 2 fields.
$.ajax({
type: 'POST',
url: '#Url.Action("DeleteUserAccount", "Home")',
data: { userName: holdUserName, password: holdPassword },
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function (data) {
if (data.length > 0) {
$("#errorMessage").css("display", "block");
}
else {
$("#errorMessage").css("display", "none");
}
$("#errorMessage").text(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Critical Error: something is wrong in the call to DeleteUserAccount for delete! Status: ' + xhr.status + '. Error: ' + thrownError.toString() + '. Response Text: ' + xhr.responseText);
}
});
// Return.
return true;
});
$(".btn-no4").click(function () {
$("#myModal4").modal("hide");
return false;
});
//$("#myModal4").on('hidden.bs.modal', function () {
// $("#myModal4").remove();
//});
});
</script>
</head>
<body>
#Html.AntiForgeryToken()
<div class="login-panel">
#*took out condition, and started with style none*#
#*#if (ViewBag.errormessage != null)
{*#
<p class="alert alert-danger" id="errorMessage" style="display:none">#ViewBag.errormessage</p>
#*}*#
<div class="form-group">
<div class="col-md-12 col-xs-12">
<h2>Delete Account</h2>
<br />
<h4 class="verify"><strong>I will need to verify your identity in order to delete your account.</strong></h4>
<br />
<h4 class="verify"><strong>Please provide the following:</strong></h4>
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="UserName">User Name</label>
<input id="UserName" type="text" value="" name="UserName">
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-xs-12">
<br />
<label class="manadatory" for="Password">Password</label>
<input id="Password" type="text" value="" name="Password">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<br />
<input class="btn btn-primary deleteUserAccount" value="Delete Account">
#Html.ActionLink("Cancel", "Index", "User", null, new { #class = "btn btn-info" })
</div>
</div>
</div>
<div class="modal fade" id="myModal4" role="dialog" display="none">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body" style="padding:10px;">
<h4 class="text-center">Are you sure you want to permanently delete your account and all it contains? Continue ?</h4>
<div class="text-center">
<a class="btn btn-info btn-yes4">Yes</a>
<a class="btn btn-default btn-no4">No</a>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

NameError (uninitialized constant Welcome4Controller::EmailMe2Mailer): RAILS

I have a simple ruby on rails form that is posted with ajax. However, I keep receiving this error:
NameError (uninitialized constant Welcome4Controller::EmailMe2Mailer):
app/controllers/welcome4_controller.rb:3:in `contact'
This is the form:
<%= form_for :contact, :remote => true, :method => :post, html: {:class => "form-stacked", id: 'contact_form' } do |f| %>
<div class="col-md-6">
<div class="input-group input-group-lg wow fadeInUp" data-wow-delay='0.8s'>
<span class="input-group-addon" id="sizing-addon1">
<i class="fa fa-user" aria-hidden="true"></i>
</span>
<input type="text" class="form-control" aria-describedby='sizing-addon1' placeholder="Full Name" name="fullname" id="fullname" required>
</div>
<div class="input-group input-group-lg wow fadeInUp" data-wow-delay='1.2s'>
<span class="input-group-addon" id="sizing-addon1">
<i class="fa fa-envelope" aria-hidden="true"></i>
</span>
<input class="form-control" aria-describedby='sizing-addon1' placeholder="Email Address" required name="email" id="email">
</div>
<div class="input-group input-group-lg wow fadeInUp" data-wow-delay='1.6s'>
<span class="input-group-addon" id="sizing-addon1">
<i class="fa fa-phone" aria-hidden="true"></i>
</span>
<input class="form-control" aria-describedby='sizing-addon1' placeholder="Phone Number (optional)" name="phone" id="phone">
</div>
</div>
<div class="col-md-6">
<div class="input-group wow fadeInUp" data-wow-delay='2s'>
<textarea class="form-control" cols="80" rows="6" name="message" placeholder="Type here..." style="width:100%" id="message" required></textarea>
</div>
<button class="btn btn-lg wow fadeInUp" data-wow-delay='2.4s' id="contact_btn"data-loading-text="<i class='fa fa-circle-o-notch fa-spin'></i> Sending" >Send Your Message</button>
</div>
<% end %>
This is the controller:
class Welcome4Controller < ApplicationController
def contact
EmailMe2Mailer.confirmation_2(params[:fullname,:email,:phone,:message]).deliver_now
render json: { success: true }, status: 200
end
def index
end
end
This is the mailer:
class EmailMe2Mailer < ApplicationMailer
default from: "**#gmail.com"
def confirmation_2(fullname,email,phone,message)
#greeting = "Hi"
#fullname = fullname
#email = email
#phone = phone
#message = message
mail to: "**#gmail.com", subject: "contact email"
end
end
This is the ajax call:
$('#contact_form').submit(function(e) {
e.preventDefault();
}).validate({
rules: {
fullname: {
required: true,
},
email: {
required: true,
email: true
},
message: {
required: true,
minlength: 5
}
},
submitHandler: function (form) {
var btn = $('#contact_btn');
btn.button('loading');
setTimeout(function() {
btn.button('reset');
}, 8000);
$.ajax({
type: 'POST',
url: '/contact',
// data: form.serialize(),
dataType: 'json',
async: true,
data: {
fullname: $('#fullname').val(),
email: $('#email').val(),
phone: $('#phone').val(),
message: $('#message').val()
},
success: function (json) {
$('#contact').hide();
$('#output').html(
'<i class="fa fa-check" aria-hidden="true" id="check" style="border-radius:50%;font-size:80px;text-align:center;color:#E81B00"></i><br><p class="lead" style="font-size:40px;">We have received your message!</p>'
).show();
}
});
return false; // for demo
}
});
It is basically complaining about passing multiple arguments to the mailer here:
EmailMe2Mailer.confirmation_2(params[:fullname,:email,:phone,:message]).deliver_now
This is where EmailMe2Mail is located:
app => mailers => email_me_2_mailer.rb
this is application_mail.rb
class ApplicationMailer < ActionMailer::Base
default from: '**#gmail.com'
layout 'mailer'
end
NameError (uninitialized constant Welcome4Controller::EmailMe2Mailer):
This is because of the file name being wrong. It should be email_me2_mailer.rb whereas you have it like email_me_2_mailer.rb Changing it to email_me2_mailer.rb should fix your problem.
Normally Rails expects the file names to be in snake_case with respect to the class names being CamelCase. You can use underscore to check the snake_case string for EmailMe2Mailer like below
"EmailMe2Mailler".underscore
=> "email_me2_mailler"

How to show a bootstrap modal success message on successfully added product to the cart

I have written a jquery for adding product to the cart and this is the partiallistofproduct.cshtml file.
<div class="container">
<div class="row">
<div class="col-sm-9 padding-right">
<div class="features_items">
<h2 class="admin-title text-center"></h2>
<!--Partial list of Products-->
#foreach (var item in Model)
{
<div class="features_items">
<!--features_items-->
<div class="col-sm-4">
<div class="product-image-wrapper">
<div class="single-products">
<div id="#item.ProductID" class="productinfo text-center">
<a href="#Url.Action("ReadProductDetails", "Home",new {id=item.ProductID })">
<img src="#Url.Content(item.ProductImage)" alt="" />
</a>
<h2>Rs #item.Price</h2>
<p>#item.ProductName</p>
#if (Session["UserName"] != null)
{
<p hidden id="userid">#Session["UserID"].ToString()</p>}
<input type="hidden" id="hdnSession" data-value="#Request.RequestContext.HttpContext.Session["Name"]" />
<input id="AddToCart" type="submit" value="Add to Cart" class="btn btn-default add-to-cart" />
</div>
<div class="product-overlay">
<div id="#item.ProductID" class="overlay-content">
<h2>Rs #item.Price</h2>
<p id="productid">#item.ProductID</p>
<a class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
</div>
</div>
</div>
</div>
</div>
</div><!--features_items-->
}
<!--Pagination part-->
#Html.PagedListPager(Model, page => Url.Action("Index", new { page, pageSize = Model.PageSize }))
showing #Model.FirstItemOnPage to #Model.LastItemOnPage of #Model.TotalItemCount Products
</div>
</div>
</div>
</div>
The following is the script file to add the product to the cart.Here i am able to add the product to the cart.
<script>
$(document).ready(function () {
//on click on add to cart class this will perform
$('.add-to-cart').click(function () {
//checking user is logged in or not otherwise redirect to login page
var sessionValue = $("#hdnSession").data('value');
var aaa = parseInt($(this).closest('div').prop('id'));
if (sessionValue != false) {
$.ajax({
url: 'Account/AddToCart',
data: { //Passing data
UserID: $("#userid").html(), //Reading text box values using Jquery
ProductID: $(this).closest('div').prop('id'),
Quantity: 1
},
type: 'POST',
dataType: 'json',
//on success message will show as an alert
success: function (data) {
if (data != null && data.success) {
alert(data.responseText);
} else {
// DoSomethingElse()
alert(data.responseText);
}
},
//on failure error message will occur
error: function (data) {
alert("error");
}
});
}
else {
//redirection to login page
window.location.replace("#Url.Action("Login", "Account")");
}
});
});
</script>
Here i want to show a bootstrap modal success message with successful adding the product to the cart. I dont know how to use bootstrap modal to show the success message.
So please help me to show a bootstrap modal success message.
Add modal in your view which you want to show on after successful addition of products to cart and add style:display:none
then inside Ajax Success function just write
$("#modal-Id").modal();

Resources