Trying to create a cart Counter Variable - c#

I am trying to create a counter variable where when a user clicks "Add To Cart" a number will appear indicating that the item was added and the number shown represents how many items are in the cart. My AddToCart controller can create a list and set it to a session variable. But I am having trouble setting the session variable without having to refresh the page. I believe it has something to do with my ajax. My main problem is that I don't know how to be able to access the new session variable so that the number next to the cart button updates when the add to cart button is pressed.
[HttpPost]
public JsonResult AddToCart(int ProductID)
{
Products productAccess = new Products();
List<ProductTier> HomeList = productAccess.IndexList();
CartAccess cartaccess = new CartAccess();
Cart product = cartaccess.FindProduct(ProductID);
product.Quantity = 1;
if (Session["cart"] == null)
{
List<Cart> ProductList = new List<Cart>();
ProductList.Add ( product );
Session["cart"] = ProductList;
Session["CartCounter"] = ProductList.Count;
}
else
{
List<Cart> Existingcart = (List<Cart>)Session["cart"];
int index = isExist(ProductID);
if (index != -1)
{
Existingcart[index].Quantity++;
}
else
{
Existingcart.Add(product);
}
Session["cart"] = Existingcart;
Session["CartCounter"] = Existingcart.Count;
}
return Json("Success");
}
function AddToCart(item) {
var ProductID = $(item).attr("ProductID");
var formData = new FormData();
formData.append("ProductID", ProductID);
$.ajax({
async: true,
type: 'POST',
contentType: false,
processData: false,
data: formData,
dataType: 'JSON',
url: '/Default/AddToCart',
success: function (data) {
if (data.sucess) {
$("#CartItem").text("Sucess Working : " + data);
window.alert("Success");
alert('Success Work');
}
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText
alert('Error - ' + errorMessage);
}
});
}
<div style="text-align:right;width:30%;margin-right:10px">
<input type="button" name="AddToCart" value="Add To Cart" class="btn btn-info" ProductID="#item.ProductID" onclick="AddToCart(this)">
</div>
<ul class="navbar-nav ml-auto">
<li class="nav-item ml-auto" style="margin-left:auto;">
#if (Session["CartCounter"] == null)
{
#Html.ActionLink("Cart", "Checkout", "DefaultController", new { #class = "nav-link", id = "CartItem" })
}
else
{
#Html.ActionLink("Cart(" + Session["CartCounter"] + ")", "Checkout", "DefaultController", new { #class = "nav-link" , id = "CartItem" })
}
</li>
</ul>
I am still new to MVC and am learning new methods, Please give me any tips I would appreciate it.

Related

The view doesn't return from controller

I want to carry data by onclick function to the next page. All data is carried along with by giving parameter but it doesn't return View from the controller. Please help me. I'm stuck in here two days this is my school project.
OnClick button:
<div class="row">
<div class="col-sm-4"></div>
<button class='btn bg-blue next' onclick="checkamt(#Model.TotalAmt)">Next</button>
</div>
Controller:
public ActionResult ComfirmPay(int e = 0, string TaxType = null, int CurrentAmt = 0)
{
ViewBag.TotalAmt = e;
ViewBag.CurrentAmt = CurrentAmt;
ViewBag.TaxType = TaxType;
return View("ComfirmPay");
}
Ajax:
function checkamt(e) {
var amount = #ViewBag.CurrentAmt;
if (amount < e) {
alert('bad');
window.location.href = 'http://localhost:22822/Home/PayTax';
}
else {
alert('good');
$.ajax({
cache: false,
url: '#Url.Action("ComfirmPay", "Home")',
data: { e: e, taxtype: taxtype, currentamt: currentamt },
beforeSend: function () {
},
success: function () {
},
complete: function () {
}
})
}
}
View:
<div class="col-md-9 col-xs-9">
<p class="text-muted">You have total <b class="text-green">#ViewBag.CurrentAmt</b> points</p>
</div>
Remove the ajax function and do this
window.location.href = "#Url.Action("ComfirmPay", "Home")" + "?e=" + e + "&taxtype=" + taxtype + "&currentamt=" + currentamt
The comment on this post explains a little more about why what you are trying to do does not work.
i think for your purpose there is no need of ajax call. you can use window.location.hrefas follows
function checkamt(e) {
var amount = #ViewBag.CurrentAmt;
if (amount < e) {
window.location.href = 'http://localhost:22822/Home/PayTax';
}
else {
window.location.href = '/Home/ComfirmPay?e='+e+'&taxtype='+taxtype+'&currentamt='+currentamt;
}
}
and in the controller
public ActionResult ComfirmPay(string e, string TaxType, string CurrentAmt)
{
ViewBag.TotalAmt = e;
ViewBag.CurrentAmt = CurrentAmt;
ViewBag.TaxType = TaxType;
return View();
}

How to access an array retrieved from controller via AJAX

I call an MVC controller via Java and AJAX. The data goes to the controller, the controller returns a List. How do I access that list? This may seem trivial, but I can't find it anywhere on google or SO. Most of the examples I've found call for using:
...
success: function (r) {
var exemptions = r.d;
...
for (var i = 0; i < exemptions.length; i++){
ddlist.appent('<option>' + exemptions[i] + '</option>');
....
}
That method, however, results in this error:
Uncaught TypeError: Cannot read property 'length' of undefined
at Object.success (6:281)
at u (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at k (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
Controller Method:
public JsonResult GetValidRecords(int year)
{
var items = new List<SelectListItem>();
var Exemptions = model.Permits.Where(m => m.Year == year).OrderBy(m => m.Exemption).OrderBy(m => m.Year).ToList();
foreach (Permit x in Exemptions)
{
items.Insert(items.Count, new SelectListItem { Text = x.Exemption.ToString(), Value = x.Exemption.ToString() });
}
return Json(items, JsonRequestBehavior.AllowGet);
}
The dropdown box:
<text>EXEMPTION RENEWAL FORM</text>
<select id="dd" name="dd" onchange="CallRenewalReport(this.value)">
<option value="">Select Year First</option>
</select>
#Html.DropDownList("ddldate", new SelectList(Model.RYearList, "ID", "Year", "Select a year"), new { #onchange = "GetGoodRecords(this.value)", #AppendDataBoundItems = "False" })
break;
The JavaScript/AJAX query:
<script type="text/javascript">
function GetGoodRecords(val) {
alert(val);
var year = val;
var RootUrl = '#Url.Content("~/")';
$.ajax({
url: RootUrl + "Reports/GetValidRecords",
data: { year: year },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var exemptions = response.d;
var ddlist = $('#dd');
ddlist.empty().append('<option selected="selected" value="0">Select Exemption</option>');
for (var i = 0; i < exemptions.length; i++) {
ddlist.append('<option>' + exemptions[i] + '</option>');
}
}
});
};
</script>
Can anyone spell this out to me in layman's terms?
Regards,
Carthax
Give this a shot in your success function:
success: function (response) {
for (var i = 0; i < response.length; i++) {
var obj = JSON.parse(JSON.stringify(response[i]));
alert(obj.Text);
}
}
This will show an alert of what is contained in each object of the response array.
(In case someone happens upon this question in google)
Based on input from #MikeMarshall, here is the solution that works:
The controller action is correct, but I'm putting it all in one place so you don't have to copy-and-paste from all over the page
public JsonResult GetValidRecords(int year)
{
var items = new List<SelectListItem>();
var Exemptions = model.Permits.Where(m => m.Year == year).OrderBy(m => m.Exemption).OrderBy(m => m.Year).ToList();
foreach (Permit x in Exemptions)
{
items.Insert(items.Count, new SelectListItem { Text = x.Exemption.ToString(), Value = x.Exemption.ToString() });
}
return Json(items, JsonRequestBehavior.AllowGet);
}
The razor code:
<text>EXEMPTION RENEWAL FORM</text>
<select id="dd" name="dd" onchange="CallRenewalReport(this.value)">
<option value="">Select Year First</option>
</select>
#Html.DropDownList("ddldate", new SelectList(Model.RYearList, "ID", "Year", "Select a year"), new { #onchange = "GetRecords(this.value)", #AppendDataBoundItems = "False" })
break;
The script:
<script type="text/javascript">
function GetRecords(val) {
alert(val);
var year = val;
var RootUrl = '#Url.Content("~/")';
$.ajax({
url: RootUrl + "Reports/GetValidRecords",
data: { year: year },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// get the dropdownlist
var ddlist = $('#dd');
// empty the dropdownlist and add "Select Exemption"
ddlist.empty().append('<option selected="selected" value="0">Select Exemption</option>');
// for each value in the response
for (var i = 0; i < response.length; i++) {
// properly query the Value and Text fields in the array
ddlist.append('<option value="' + response[i].Value + '">' + response[i].Text + '</option>');
}
}
});
};
</script>

drop down list refresh in razor

I have a drop down list which represent states and according to selected state, I need to refresh City drop down list which represent the cities in the selected state. How can I refresh the city drop down ?
Here is my code :
public class AccountController : Controller
{
public static List<SelectListItem> StateListItem()
{
var stateList = new List<SeraydarBL.Accounts.State>();
var selectListItems = new List<SelectListItem>();
stateList = SeraydarBL.Accounts.SelectStates();
foreach (var state in stateList)
{
var selectListItem = new SelectListItem();
selectListItem.Text = state.name;
selectListItem.Value = state.id.ToString();
selectListItems.Add(selectListItem);
}
return selectListItems;
}
}
here is the razor :
#using (Html.BeginForm())
{
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
//-------------------------------------------------------
var stateList = new List<SelectListItem>();
stateList = AccountController.StateListItem();
}
#Html.LabelFor(model => model.StateId)
#Html.DropDownListFor(model => model.StateId, stateList, " Select your State ...")
#Html.ValidationMessageFor(m => m.StateId)
#*HERE MUST BE THE DROP DOWN LIST OF CITIES*#
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
<script>
$('#StateId').change(function () {
});
</script>
}
You can achieve this using jquery ajax call.
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#StateId").change(function () {
$("#CityId").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCity")',
dataType: 'json',
data: { id: $("#StateId").val() },
success: function (cities) {
$.each(cities, function (i, city) {
$("#CityId").append('<option value="' + city.Value + '">' +``});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
refer few articles
http://www.codeproject.com/Articles/730953/Cascading-Dropdown-List-With-MVC-LINQ-to-SQL-and-A
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-cascading-dropdownlist-in-mvc-4-using-razor/

Refresh page after POST

I have created a solution where I post an array of string to my controller.
The setup works fine but I have to manually refresh the page before I can see the results of my method.
How do I make the solution refresh the page after I posted?
My view (tree.html):
<form>
<textarea class="form-control auto-input-field" rows="10" cols="80" id="autoGenerateInputField" ng-model="fighterList" ng-list="/\n/" />
<input class="btn btn-primary" type="submit" ng-click="GenerateTournamentTree(data)" value="Generer kamptræ" />
</form>
My js (angular):
$scope.GenerateTournamentTree = function(matches){
var stringOfFighters = new Array();
var categoryId = $scope.CategoryId;
stringOfFighters = $scope.fighterList;
var postData = { fighters: stringOfFighters };
if (stringOfFighters != null) {
$.ajax({
type: "POST",
url: "/Api/Match/GenerateTournamentTree",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(stringOfFighters),
success: function (data) {
alert(data.Result);
},
dataType: "json",
traditional: true
});
} else {
$modal.open({
templateUrl: 'generateTreeMessage.html',
scope: $scope,
controller: function ($scope) {
$scope.ok = function () {
$scope.$dismiss();
}
$scope.cancel = function () {
$scope.$dismiss();
}
}
})
}
}
My controller:
[Route("api/Match/GenerateTournamentTree")]
public IHttpActionResult GenerateTournamentTree(List<String> fighters)
{
fighters.Shuffle();
var nodeTree = InsertNode(new TreeNode(), fighters);
var matches = new List<MatchRecord>();
GenerateMatch(matches, nodeTree);
foreach(var match in matches)
{
match.CategoryId = new Guid("425d750e-56bd-412c-8a48-38c2fbe5b24c");
match.EventId = 18;
}
db.Matches.AddRange(matches);
try
{
db.SaveChanges();
}
catch (DbUpdateException)
{
throw;
}
//return CreatedAtRoute("DefaultApi", new { id = "18" }, fighters);
//I tried this but with no succes.
return Json(new { Result = fighters });
//this is only created to return something.
}

Change button status (MVC)

I wanna make twitter like microblog site which other users can follow my posts.
For that i made page with all currently registered users. In front of each name there is button to follow/unfollow user. (Like in Twitter)
View -
#{
ViewBag.Title = "Users";
}
#model MembershipUserCollection
#foreach (MembershipUser item in Model)
{
if(User.Identity.Name != item.UserName)
{
<li>#item.UserName
<span id="sp-#item.UserName"><input id="#item.UserName" name="submit" type="submit" value="Follow" class="follow-user fg-button ui-state-default"/></span>
</li>
}
}
<script type="text/javascript">
$(".follow-user").live("click", function (e) {
e.preventDefault();
var data = $(this).attr("id");
var spid = '#sp-' + data;
var btnid = '#' + data;
var val = $(this).attr('value');
$.ajax({
type: "POST",
url: "User/FollowUser",
data: { id: data },
cache: false,
dataType: "json",
success: function () {
if (val == 'Follow') {
$(btnid).attr('value', 'Unfollow');
}
else {
$(btnid).attr('value', 'Follow');
}
}
});
});
</script>
Controller -
public ActionResult Index()
{
return View(Membership.GetAllUsers());
}
public void FollowUser(string id)
{
ViewData["test"] = "test";
var n = FollowingUser.CreateFollowingUser(0);
n.FollowingId = id;
n.FollowerId = User.Identity.Name;
string message = string.Empty;
var list = new List<FollowingUser>();
list = (from a in db.FollowingUsers where a.FollowerId == User.Identity.Name && a.FollowingId == id select a).ToList();
if (list.Count() == 0)
{
try
{
db.AddToFollowingUsers(n);
db.SaveChanges();
}
catch (Exception ex)
{
message = ex.Message;
}
}
else
{
db.DeleteObject((from a in db.FollowingUsers where a.FollowerId == User.Identity.Name select a).FirstOrDefault());
db.SaveChanges();
}
}
FollowingUsers Table -
Now i wanna change button status on page load checking database whether he is already followed or not.
Ex- If user already followed it should display like below.
When you show this view to a user where this button is displayed, Load the status also, if the person is following or not.
public ActionResult Index()
{
var model = new MemberShipViewModel();
//We check here if the logged in user is already following the user being viewd
foreach(var member in Membership.GetAllUsers())
{
var user = (from a in db.FollowingUsers where a.FollowerId == User.Identity.Name && a.FollowingId == member.UserName select a).FirstOrDefault();
model.Members.Add(new Member{UserName = member.UserName,IsFollowing=user!=null});
}
//This line will remove the logged in user.
model.Members.Remove(model.Members.First(m=>m.UserName==User.Identity.Name));
return view(model);
}
In your index view model, you need to make some changes.
#model MemberShipViewModel
#foreach (var item in Model)
{
<li>#item.UserName
if(!item.IsFollowing)
{
<span id="sp-#item.UserName"><input id="#item.UserName" name="submit" type="submit" value="Follow" class="follow-user fg-button ui-state-default"/></span>
}
else
{
<span id="sp-#item.UserName"><input id="#item.UserName" name="submit" type="submit" value="Follow" class="unfollow-user fg-button ui-state-default"/></span>
}
</li>
}
$(".follow-user").live("click", function (e) {
e.preventDefault();
var data = $(this).attr("id");
var spid = '#sp-' + data;
var btnid = '#' + data;
var val = $(this).attr('value');
$.ajax({
type: "POST",
url: "User/FollowUser",
data: { id: data },
cache: false,
dataType: "json",
success: function () {
if (val == 'Follow') {
$(btnid).attr('value', 'Unfollow');
}
else {
$(btnid).attr('value', 'Follow');
}
}
});
});
You need to write some javascript now. Nobody is going to write full software for you.
Seems you are missing very basic programming skills.
cheers

Categories