The view doesn't return from controller - c#

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();
}

Related

Trying to create a cart Counter Variable

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.

Ajax callback issue

I got an project in dotnet and i'm trying to use GoogleCharts, but it's not working.
The project is on .net mvc
Here is my code:
Views->Sensor->Chart.cshtml
#{
ViewData["Title"] = "Chart";
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(LoadData);
function LoadData() {
$.ajax({
url: '#Url.Action("ChartJson","Sensor")',
dataType: "json",
type: "GET",
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
toastr.error(err.message);
},
success: function(data) {
CreateChart(data);
return false;
}
});
return false;
}
function CreateChart(data) {
var dataArray = [
['Tag', 'Average value']
];
$.each(data, function(i, item) {
dataArray.push([item.tag, item.value]);
});
var data = google.visualization.arrayToDataTable(dataArray);
var options = {
title: 'Sensor data per coutry and region',
chartArea: {
width: '50%'
},
colors: ['#b0120a', '#ffab91'],
hAxis: {
title: 'Arithmetic average',
minValue: 0
},
vAxis: {
title: 'Tag'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
return false;
}
</script>
This view is loaded on the url, but there is no graph on it.
I thied to debug the controller class, but the ChartJson() method is never called.
This is the two methods on the controller for the charts draw routine:
Controllers->SensorController.cs
public IActionResult Chart()
{
return View();
}
public JsonResult ChartJson()
{
var sensors = from s in _context.Sensor select s;
var sensorsList = sensors.ToList();
Console.WriteLine("Entrou");
List<ChartData> listChart = new List<ChartData>();
foreach (Sensor s in sensorsList)
{
int value;
bool isNumeric = int.TryParse(s.value, out value);
if (!isNumeric)
continue;
string tag = s.country + "." + s.region;
for (int i = 0; i < listChart.Count; i++)
{
if (listChart[i].tag.Equals(tag))
{
listChart[i].AddValue(value);
break;
}
if (i == listChart.Count - 1)
{
listChart.Add(new ChartData(tag));
break;
}
}
}
return Json(listChart);
}
Can anyone help me? Thanks.

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.
}

Get data from a controller, return as json and preview in cshtml

I have a controller that I get result exampleController.cs:
public expChart{
...
public ActionResult ByContainer(int id)
{
var elementIds = _systemSettings.Z3FromZBIds; // CritialWorkPermitIds;
var kpiElements = CacheService.AllVisibleElements
.Where(x => elementIds.Contains(x.Id)).ToList();
var container = _kpiContainerService.Find(id);
var result = _kpiTrendService.MonthByContainer(kpiElements, container);
return AsJson(result);
}
}
I call it in example.cshtml:
<div class="panel" style="display: none;" id="bottom-area-trend-charts" ng-ontroller="exampleController">
<div >
TEST
{{element.Name}}
</div>
</div>
I think it is something wrong with my calling. How can I call the result in my controller?
Thanks in advance
Use something like this:
<script type="text/javascript">
$(function () {
$.ajax({
url: "/YourController/ByContainer",
type: "GET",
dataType: 'html',
data: { id: 10 }, // the value id for call your controller
success: function (data) {
// make sure your result variable is enumerable.
$(data).each(function (index, element) {
$("#bottom-area-trend-charts div").append("<p>" + element.Name + "</p>");
});
},
error: function (xqr, errorMessage) {
alert(errorMessage);
}
});
});
</script>
And change your action to this:
public JsonResult ByContainer(int id)
{
var elementIds = _systemSettings.Z3FromZBIds; // CritialWorkPermitIds;
var kpiElements = CacheService.AllVisibleElements
.Where(x => elementIds.Contains(x.Id)).ToList();
var container = _kpiContainerService.Find(id);
var result = _kpiTrendService.MonthByContainer(kpiElements, container);
return Json(result, JsonRequestBehavior.AllowGet);
}

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