I am trying to add an item from a string to insert into a table along with the other information. I have followed a tutorial for a shopping cart and I am in need of adding the total cost to the record. I have the item in the array and have added what I believe to be the items I need. What I am having an issue with is implementing it in the controller side of the project. Below is the code I have, I am not 100% sure if what I added for the total price is correct. This should be in decimal form. thank for your help.
Shopping Cart CSHTML page. This is not the whole page just relevant parts.
using (Html.BeginForm("AddOrder", "Parts", new { id = "f" }))
{
<table id="tableOrder" class="table table-hover">
<tr>
<th>Part Number</th>
<th>Unit Price</th>
<th>Qty Selected</th>
<th>Description</th>
<th>Total Price</th>
</tr>
#foreach (var parts in Model)
{
<tr>
<td>#parts.Material</td>
<td>#string.Format("{0:C2}", parts.SellingPrice)</td>
<td>#parts.QtySelected</td>
<td>#parts.Description</td>
<td>#string.Format("{0:C2}", (parts.SellingPrice * parts.QtySelected))</td>
</tr>
totalOrder += (parts.QtySelected * parts.SellingPrice);
#Html.HiddenFor(p => parts.Material)
#Html.HiddenFor(p => parts.QtySelected)
}
</table>
<!-- TOTAL PRICE-->
<h4 style="margin-left: 66%;">Total : <span class="label label-info">#string.Format("{0:C2}", totalOrder)</span></h4>
#Html.HiddenFor(p => totalOrder)
<div class="modal-footer">
<button type="button" class="btn btn-secondary" id="close" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="SaveOrder" data-toggle="modal" data-target="#additionalInfo">Save Order</button>
</div> <!-- MODAL FOOTER-->
}
Java Script portion.
$("#SaveOrder").click(function () {
var $form = $(this).closest('form');
var dataPart = $form.serializeArray();
console.log(dataPart);
var arrIdPart = [];
var arrQtyPart = [];
var totalPrice = [];
for (i = 0; i < dataPart.length; i++)
{
if (dataPart[i].name == 'parts.Material')
{
arrIdPart.push(dataPart[i].value);
}
else if (dataPart[i].name == 'parts.QtySelected')
{
arrQtyPart.push(dataPart[i].value);
}
else if (dataPart[i].name == 'totalOrder')
{
totalPrice.push(dataPart[i].value);
}
}
$.ajax({
type: 'POST',
url: '#Url.Action("AddOrder", "Parts")',
data: { arrIdPart, arrQtyPart },
success: function (response) {
if(response.data == true)
{
alert("Order has saved successfully ");
}
else
{
alert("Order did not save successfully ! ");
}
},
error: function (error) {
alert("Order did not collect data successfully ! ");
}
});
});
Here is the controller action. I have added the parts to all of these that have to do with totalPrice. The issue is how to implement it in the record add to customer.
[HttpPost]
public ActionResult AddOrder(string[] arrIdPart, int[] arrQtyPart, decimal[] totalPrice)
{
int countPart = arrIdPart.Length;
int CompanyId = (int)Session["CompanyId"];
bool statusTran = false;
EDIT - added
decimal totPrice = totalPrice.Length;
CustomerEntities _context = new CustomerEntities();
using (DbContextTransaction dbTran = _context.Database.BeginTransaction())
{
try
{
CompanyNames customer = _context.CompanyNames.Find(CompanyId);
if (customer != null)
{
EDIT - Changed this
customer.Ordered.Add(new Orders { OrderDate = DateTime.Now, TotalPrice = totPrice });
}
Orders orderSelected = customer.Ordered.LastOrDefault();
if (orderSelected != null)
{
for (int i = 0; i < countPart; i++)
{
Parts selectedPart = _context.Parts.Find(arrIdPart[i]);
orderSelected.OrderDetail.Add(new OrderDetails { Parts = selectedPart, Quantity = arrQtyPart[i] });
}
}
//Save Changes
int countResult = _context.SaveChanges();
//Commit Transaction
dbTran.Commit();
if (countPart > 0)
{
statusTran = true;
partsList.Clear();
}
}
catch (Exception)
{
dbTran.Rollback();
}
}
return Json(new { data = statusTran }, JsonRequestBehavior.AllowGet);
}
}
However I am not getting anything for totalOrder in the script. Says its null. But in my 'console.log(dataPart);' In the console it is there with the name totalOrder.
Not saying it's the final answer but I can't put multiline code in a comment..
I wish to point out that you don't post the total price you calculated, to the server:
type: 'POST',
url: '#Url.Action("AddOrder", "Parts")',
data: { arrIdPart, arrQtyPart }, //look, no totalprice data? You did all those efforts to calc it and then did nothing with it?
success: function (response) {
if(response.data == true)
totalPrice should probably be called arrSubtotalPart by the way, for consistency..
Warning: The server receives the items and the quantities, it should work the price out from that rather than let the end user dictate how much he wants to pay for an order by manipulating the JavaScript
Related
I have a variable in my jQuery called storedDealer that I want to be filled with the option text when a drop-down item is selected:
var storedDealer = '';
$(document).ready(function () {
let dealerId = #Model.DealerID;
if (0 < dealerId.length) {
$("#DealerID option[value='dealerId'']").attr('selected', 'selected');
$('#dealershipName').val(storedDealer);
}
$('#DealerID').on("change", function () {
storedDealer = this.value;
});
});
function getDealers(el) {
$.get("#Url.Action("GetDealers", "Admin")?region=" + $(el).val(), function (res) {
var markup = "";
for (var i = 0; i < res.length; i++) {
markup += '<option value='+res[i].Value+'>'+res[i].Text+"</option>"
}
$('#DealerID').prop('disabled', false);
$("#DealerID").html(markup).show();
});
}
My HTML has a little bit of C# Razor code that is the only place the DealerID is defined. I have added the <var id="dealershipName"> item:
<tr>
<td align="right">Dealership:</td>
<td>#Html.DropDownListFor(m => m.DealerID, new List<SelectListItem>())</td>
<td><var id="dealershipName" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
<td></td>
</tr>
I would not have thought the Razor variables would be visible by jQuery, but they somehow seem to work.
But when the search is submitted, the page refreshes. Now the drop-down list is reset and the <var> field is blank.
That <var> field is what I added, and I am trying to get to work.
How can I get the value to stay after the form reloads?
I think you can try to use Session,here is a demo for .net6.Each time the slected value is changed,change storedDealer and the session data.And when you refresh the page,if the session data is not null,storedDealer will be set with the session data:
Program.cs:
builder.Services.AddControllersWithViews();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromDays(1);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
actions:
public IActionResult Test(){
return View();
}
public void SetSession(string storedDealer) {
HttpContext.Session.SetString("storedDealer", storedDealer);
}
Test view:
var storedDealer = "";
$(document).ready(function () {
let dealerId = #Model.DealerID;
if (0 < dealerId.length) {
$("#DealerID option[value='dealerId'']").attr('selected', 'selected');
if(storedDealer==""&&"#(string.IsNullOrEmpty(Context.Session.GetString("storedDealer")))"!=True)
{
storedDealer = "#Context.Session.GetString("storedDealer")";
}
$('#dealershipName').val(storedDealer);
}
$('#DealerID').on("change", function () {
storedDealer = this.value;
$.ajax({
type: "GET",
url: "SetSession",
data: {storedDealer:$("#IdSelectIdEmpleado").val()},
});
});
});
Hi everyone and thanks for reading this message at first.
I am currently struggling with an ASP.Net MVC Framework project for passing data between views.
I have a controller Model with Index View and a javascript that helps me getting ids of objects clicked on a 3d model rendered in a canvas. Here is the view :
<div class="col-md-10">
<canvas id="viewer"></canvas>
</div>
<div class="col-md-2">
<btn id="AddEventObjects" class="btn btn-eiffage-red">Create a task</btn>
<table id="selectedElements" class="table table-striped">
<thead><tr><th>Selected parts</th></tr></thead>
</table>
</div>
<script type="text/javascript">
var viewer = new xViewer('viewer');
var selectedIds = [];
viewer.on('loaded',
() => {
viewer.start();
});
viewer.on('pick', function (args) {
if (args == null || args.id == null) {
return;
}
var id = args.id;
//If the id was previously clicked then remove it from the list and remove the highlight
if (selectedIds.includes(id)) {
var index = selectedIds.indexOf(id);
selectedIds.splice(index, 1);
} else {
selectedIds.push(id);
}
//Add elements to the table
var table = document.getElementById('selectedElements');
var oldtbody = document.getElementById('selectedElementsBody');
if (oldtbody) {
oldtbody.remove();
}
var tbody = document.createElement('tbody');
tbody.id = "selectedElementsBody";
for (var i = 0; i < selectedIds.length; i++) {
var row = document.createElement('tr');
var cell = document.createElement('td');
cell.textContent = selectedProperties[i];
row.appendChild(cell);
tbody.appendChild(row);
table.appendChild(tbody);
}
});
viewer.load('../Content/3d/Maintenance.wexbim');
</script>
With the script under I would like to open another window passing the selectedIds array :
<script type="text/javascript">
$('#AddEventObjects').click(function () {
$.ajax({
url: "#(Url.Action("AddEventObjects", "Planning"))",
type: "GET",
dataType : "json",
data: { selectedObjects: selectedIds},
cache: false,
async: true,
traditional: true,
success: function (data) {
window.location = "/Planning/AddEventObjects";
},
error: function () {
alert("error");
}
});
});
</script>
Knowing that my controller Planning has an action called AddEventObjects:
public ActionResult AddEventObjects(string[] selectedObjects) {
ViewBag.Title = "Ajout intervention";
var addEventObjectsViewModel = new AddEventObjectsViewModel {
Title = "",
StartTime = "",
EndTime = "",
AllUsers = _context.Users.ToList(),
SelectedUsers = new List<ApplicationUser>(),
PostedUsers = new PostedUsers(),
ObjectsIds = selectedObjects.ToList(),
};
addEventObjectsViewModel.PostedUsers.SelectedIds = addEventObjectsViewModel.SelectedUsers.Select(x => x.Id).ToArray();
return View(addEventObjectsViewModel);
}
I would like it to open the following view that displays the selectedIds :
#model Maintenance.Web.Models.AddEventObjectsViewModel
using (Html.BeginForm("AddEvent", "Planning", FormMethod.Post, new { #class = "form-horizontal", role = "form" })) {
#Html.AntiForgeryToken()
<h4>Créer une nouvelle intervention</h4>
<div class="form-horizontal col-md-12">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-row col-md-12">
<div class="col-md-4">
<div class="form-group">
#Html.LabelFor(m => m.ObjectsIds, htmlAttributes: new { #class = "control-label" })
<table class="table table-striped" style="width:100%; margin-top:20px">
<thead>
<tr>
<th>Id</th>
</tr>
</thead>
#if (Model != null) {
foreach (var objectId in Model.ObjectsIds) {
<tr>
<td>#objectId</td>
</tr>
}
}
</table>
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<div class="col-md-10">
<input type="submit" class="btn btn-eiffage-red" value="Ajouter" />
</div>
</div>
</div>
}
With a more basic question : how can I pass an array from a javascript in a view to another view?
Thanks a lot for your help.
If you are passing an array of data, there are a few ways. The easiest of ways is to do the following. Join the array IDS into a comma separated string:
var idList = data.PostedUsers.SelectedIds.join(); //comma sep list
window.location = "/Planning/AddEventObjects?ids=" + idList;
This would work with what you have very simply; it will build a URL like:
/Planning/AddEventObjects?ids=1,2,3,4
In the backend, you have a "string ids" parameter, and split it by comma, and use the IDs however you need to.
Thanks Brian Mains!
I went with passing data in the url as you suggested.
I just used Json serialized data instead of coma separated values :
<a id="CreateEvent" class="btn" href="">Créer une intervention</a>
...
var createLink = "/Planning/AddEventObjects?ids=" + JSON.stringify(model.ids);
$('#CreateEvent').attr("href", createLink);
And then in my controller :
public ActionResult AddEventObjects(string ids) {
if (ids == null) {
return HttpNotFound();
}
string[] objectIds = JsonConvert.DeserializeObject<string[]>(ids);
}
I have wrote code to add items on cart. I can add items only if reload the page. But I want to add items without reloading the page.
Here is my Script:
<script>
$(document).ready(function () {
$("#addToCart").click(function () {
var productId = $('#productId').val();
var productName = $('#productName').val();
var unitPrice = $('#unitPrice').val();
var quantity = $('#quantity').val();
var image = $('#Image').val();
addItemToCart(productId, productName, quantity, unitPrice, image);
});
});
function addItemToCart(productId, productName, quantity, unitPrice, image) {
var getProduct = {};
getProduct.Name = productName;
getProduct.Image = image;
getProduct.unitPrice = unitPrice;
var product = {};
product.Product = getProduct;
product.ProductId = productId;
product.Quantity = parseInt(quantity);
product.Price = parseFloat(unitPrice) * parseInt(quantity);
product.Product.unitPrice = unitPrice;
$.ajax({
type: "POST",
url: "/Product/GetCartData",
data: JSON.stringify(product),
contentType: "application/json;charset=UTF-8",
dataType: "json",
crossDomain: true,
success:function()
{
var url = '/Product/Details?ProductId=' + productId;
window.location.href = url;
}
});
}
</script>
Here is my action addtocart
public JsonResult GetCartData(OrderDetail details)
{
if (Session["OrderDetails"] != null)
{
orderDetails = (List<OrderDetail>)Session["OrderDetails"];
int flag = 0;
foreach (var order in orderDetails)
{
if (order.ProductId == details.ProductId)
{
order.Quantity += details.Quantity;
order.Price += details.Price;
flag = 1;
}
}
if (flag == 0)
{
orderDetails.Add(details);
}
Session["OrderDetails"] = orderDetails;
}
else
{
orderDetails = new List<OrderDetail>();
orderDetails.Add(details);
Session["OrderDetails"] = orderDetails;
}
return Json(orderDetails);
}
here is the layoutpage
#using EFreshStore.Models.Context
#using EFreshStore.Models.Context
#{
List<OrderDetail> orderDetails =new List<OrderDetail>();
int countItem = 0;
string totalAmount = "0";
if (Session["OrderDetails"] != null)
{
orderDetails = (List<OrderDetail>)Session["OrderDetails"];
countItem = orderDetails.Count;
totalAmount=orderDetails.Sum(c => c.Price).ToString();
}
List<ProductUnit> productUnits = (List<ProductUnit>)Session["ProductUnit"];
}
<!DOCTYPE html>
<html class="no-js" lang="">
<head>
</head>
<body class="home-one">
<div class="header-chart">
<ul class="list-inline">
<li><i class="fa fa-cart-arrow-down"></i></li>
<li class="chart-li">
My cart
<ul>
<li>
<div class="header-chart-dropdown">
#if (orderDetails!= null)
{
foreach (var item in orderDetails)
{
<div class="header-chart-dropdown-list">
<div class="dropdown-chart-left floatleft">
#foreach (var units in productUnits)
{
if (units.ProductId == #item.ProductId)
{
<img src="~/#units.ProductImages.FirstOrDefault().ImageLocation" width="60px" height="60px"alt="cart">
}
}
</div>
<div class="dropdown-chart-right">
<h2 class="shopItemTitle">
#item.Product.Name
</h2>
<h3>Qty: #item.Quantity</h3>
<h4>৳ #item.Price</h4>
</div>
</div>
}
}
<div class="chart-checkout">
<p>subtotal<span>৳ #totalAmount</span></p>
<button type="button" onclick="window.location.href ='/Order/Cart'" class="btn btn-default">Chckout</button>
</div>
</div>
</li>
</ul>
</li>
<li>#countItem items</li>
</ul>
</div>
</body>
</html>
Cart is on a layout page.
I have created a button click event function to take data.
Then make another function to add items on cart
Is it possible on this ajax function?
It depends on how your entire API is structured. I can see that you are calling POST on "/Product/GetCartData". This is returning a product id. If you can, by the information you have in the client, show the actual product in the cart using that product id, then it can be solved. But it is hard to see as you have not provided more code.
What i am guessing is that you should have an API GET endpoint for the products currently in the cart, and then in the response function of the POST request you should send out a new GET ajax request, where you ask for the products currently in the cart. Then you would avoid a page refresh.
My group and I have been struggling to find an answer to this for our website and we've finally taken the step to asking the community for some help!
The goal is the try and link the button of our website to "remove from cart" and set the database back to 0 as well as refresh the page and show the decrementation taking place.
The shopping cart view's javascript does not seem to be working, but I'm not sure if this is ultimately the issue. We've followed many guides such as the MVC music store and ASP.NET documentations.
Index.cshtml:
script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// Document.ready -> link up remove event handler
$(".RemoveLink").click(function () {
// Get the id from the link
var recordToDelete = $(this).attr("data-id");
if (recordToDelete != '') {
// Perform the ajax post
$.post("/ShoppingCart/RemoveFromCart", { "id": recordToDelete },
function (data) {
// Successful requests get here
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
});
}
});
});
function handleUpdate() {
// Load and deserialize the returned JSON data
var json = context.get_data();
var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data.DeleteId).fadeOut('slow');
} else {
$('#item-count-' + data.DeleteId).text(data.ItemCount);
}
$('#cart-total').text(data.CartTotal);
$('#update-message').text(data.Message);
$('#cart-status').text('Cart (' + data.CartCount + ')');
}
</script>
<h3>
<em>Review</em> your cart:
</h3>
<div id="update-message">
</div>
<div style="height:600px; overflow:auto; padding-top: 50px; margin-left: 200px; width: 1050px; ">
<table id="cart-summary" border="1" frame="void" rules="rows" style="width:100%;margin-left:auto; margin-right: auto;">
<tr class="data-table">
<th colspan="1">
Item(s)
</th>
<th colspan="1" style="text-align:center;">
Price
</th>
<th colspan="1" style="text-align:center;">
Quantity
</th>
<th colspan="1" style="text-align:center;">
Total
</th>
<th></th>
</tr>
#foreach (var item in Model.CartItem)
{
<tr>
<td style="margin:auto;width:500px;">
<div style="float:left;">
<a href=#Url.Content(String.Format("~/Books/Details/{0}", item.Book.id))>
<img class="img-responsive" src="#Url.Content(String.Format("~/Content/img/books/{0}.jpg",item.Book.ISBN))" style="width: 100px; height: 150px;" />
</a>
</div>
<div style="margin-top:37px;">
<a href=#Url.Content(String.Format("~/Books/Details/{0}", item.Book.id))>
<span>#Html.DisplayFor(modelItem => item.Book.Title)</span><br />
</a>
<span style="text-align:left;">#Html.DisplayFor(modelItem => item.Book.Author)</span><br /><br />
<span style="text-align:left">ISBN: #Html.DisplayFor(modelItem => item.Book.ISBN)</span>
</div>
</td>
<td>
<p style="text-align:center;">#item.Book.PriceNew</p>
</td>
<td>
<p style="text-align:center;">#item.Quantity</p>
Remove from cart
<!--data-url='Url.Content("~/ShoppingCart/RemoveFromCart")'>
Remove from cart
</a>-->
</td>
<td>
<p>#Model.CartTotal</p>
</td>
</tr>
}
<tr>
<td></td>
<td>
<p style="padding-top:15px;"></p>
<br />
<button type="button">
#Html.ActionLink("Back to List", "../Books/Index")
</button>
</td>
<td></td>
<td id="cart-total">
<p style="padding-top: 10px;font-weight:bold;color:rgb(179,0,0);font-size:18px;">Subtotal: #Model.CartTotal</p>
<button type="button">
#Html.ActionLink("Checkout!", "AddressAndPayment", "Checkout")
</button>
</td>
</tr>
</table>
</div>
The next set of code is the C# code.
Cart.cs:
public int RemoveFromCart(int id)
{
var cartItem = bookDb.Carts.Single(
c => (c.CartId == ShoppingCartId)
&& c.RecordId == id);
int itemCount = 0;
if (cartItem != null)
{
if (cartItem.Quantity > 1)
{
cartItem.Quantity--;
itemCount = cartItem.Quantity;
}
else
{
bookDb.Carts.Remove(cartItem);
}
bookDb.SaveChanges();
}
return itemCount;
}
Finally to complete the MVC set of code which relate to each other...We also believe there may be an error here. Again, we just aren't experienced enough to know.
ShoppingCartController.cs:
// GET: ShoppingCart
public ActionResult Index()
{
var cart = ShoppingCart.GetCart(this.HttpContext);
// Set up our View Model
var viewModel = new ShoppingCartViewModel
{
CartItem = cart.GetCartItems(),
CartTotal = cart.GetTotal()
};
return View(viewModel);
}
// GET: Book/Details/5
// Button that allows you to add to the cart you will be redirected to the Shopping cart index page
public ActionResult AddToCart(string id)
{
var addedBook = bookdb.Books.Single(book => book.ISBN == id);
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(addedBook);
bookdb.SaveChanges();
return RedirectToAction("Index");
}
// this is attached to the remove to cart button in the shopping cart index page, the index page will then reload
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Retrieve the current user's shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the book to display confirmation
string bookName = bookdb.Carts.Single(book => book.RecordId == id).Book.Title;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(bookName) + " has been removed from the shopping cart",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
//return view();
return Json(results);
}
Thanks a bunch!
Index.cshtml
<script>
$(document).on('click', '.del-CartDetail', function () {
var id = $(this).data("id");
$("#hdnCartDetailId").val(id);
$("#modal-del-cartdetail").modal({
backdrop: 'static',
keyboard: false,
show: true
});
});
$("#btnModalSubmit").click(function () {
var buttonText = $("#btnModalSubmit").html();
$("#btnModalSubmit").attr('disabled', '').html('<i class="fa fa-spinner fa-spin"></i> ' + buttonText);
var id = $("#hdnCartDetailId").val();
$.ajax({
url: '/CartDetail/DeleteCartDetail',
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ Id: id }),
success: function (result) {
debugger;
if (result.success) {
$('#modal-del-cartdetail .close').click();
//Page redirect after delete record
window.location.reload();
$('#modal-del-cartdetail').show();
INTAPP.Util.Notification(true, "Selected Cart(s) have been successfully deleted.");
} else {
INTAPP.Util.HandleLogout(data.message);
INTAPP.Util.Notification(false, "Some error occured while deleting selected Cart.");
}
$("#btnModalSubmit").attr('disabled', null).html('Submit');
},
error: function (xhr, status, error) {
INTAPP.Util.Notification(false, error);
$("#btnModalSubmit").attr('disabled', null).html('Submit');
}
});
});
</script>
#Html.Partial("ConfirmModal", new ModalViewModel
{
Id = "modal-del-cartdetail",
IsAlertModel = false,
Title = "Delete Product",
Message = "Are you sure you want to delete the cart detail?",
HiddenElementId = "hdnCartDetailId"
})
I'm working on a project at the moment using angular JS.
I've used a directive to switch from advanced search so that the results can be viewed on its own page. basically when submit is clicked, the advanced search is hidden and only results table can be seen. so now, once on results table, I want to be able to go back to that advanced search to the point before I hit that submit button, the data is still there, I have just reversed the directive in a way. any suggestions would be greatly appreciated, this is all fairly new to me.
thanks! (please note, my search controller uses TypeScript)
this is being called just under the submit button on the search_partial.html
<div class="submit">
<button class="btn btn-primary" type="button" name="Submit" ng-click="vm.validateForm()" ng-disabled="!(!!vm.hospitalNumberInput || !!vm.nhsNumberInput || !!vm.fullNameInput || !!vm.sexInput || vm.yearOfBirthInput || !!vm.streetInput || !!vm.cityInput
|| !!vm.postCodeInput || !!vm.chosenCountry)">Search</button>
Clear all
</div>
</form>
<section>
<div id="searchDirective" search-results patients="vm.results" class="ng-hide"></div>
</section>
and I have a directives file called search.results.directive.js
(function () {
angular
.module('app.search.results')
.directive('searchResults', function() {
return {
restrict: 'AE',
templateUrl: 'app/search/Partials/result_partial.html',
scope: {
patients: '='
}
};
});
})();
so what I'm trying to do now that I can see the results-partial.html on the screen in front of me, I want to be able to click a back button on there to take me back to the search-partial.html at the point before the user clicked that submit button so that the data in the boxes can be altered if needs be or more search data added. (at the moment I have a back href going to the home url, it works for now, but that's what im hoping to replace).
results-partial.html:
<main class="container">
<!-- RESULT -->
<section class="result-display">
<form>
<div class="searchresults content table-responsive">
<h2>Search Criteria: </h2>
<h2> Search Results: {{patients.length}} patients found</h2>
<table class="table resultstable table-striped">
<thead>
<tr class="theading">
<th>Hospital number</th>
<th>NHS Number</th>
<th>Full Name</th>
<th>DOB</th>
<th>Sex</th>
</tr>
</thead>
<!--repeated simply for style insight-->
<tbody>
<tr ng-repeat="patient in patients">
<td>{{patient.resource.hospitalNumber}}</td>
<td>{{patient.resource.nhsNumber}}</td>
<td>{{patient.resource.nameString}}</td>
<td>{{patient.resource.birthDate}}</td>
<td>{{patient.resource.gender.toUpperCase()}}</td>
</tr>
</tbody>
</table>
</div>
<a href style="float: right; font-size:120%;" onclick="location.href='http://localhost:3000/';"><i class="close"></i><u>Back to Search</u></a>
</form>
</section>
</main>
If I understand the question right, you want to preserve the values in the input.
You can use a factory or value to store the data.
myApp.factory('DataHolder', function (){
return data;
});
// Or, with value
myApp.value('DataHolder', data);
And in your controller you can access that data anywhere.
myApp.controller('Ctrl', function ($scope, DataHolder){
$scope.data = DataHolder;
});
So when you come back to the back state, if you have data stored you can get it back to show it.
fixed it. managed to get it working my changing the flag to false with "returnToSearch()" function at the bottom.
createDisplayParams(): void {
// add in search params to display params
var paramTypes: string[] = [];
for (var i: number = 0; i < this.searchParams.length; ++i) {
var objectIndex: number = paramTypes.indexOf(this.searchParams[i].ParamName);
if (objectIndex === -1) {
// if param name dosen't exist, add it to the paramTypes
paramTypes.push(this.searchParams[i].ParamName);
}
}
for (var j: number = 0; j < paramTypes.length; ++j) {
var valueParams: core.ISearchParam[] = [];
valueParams =_.filter(this.searchParams, searchParam => { //lodash
return searchParam.ParamName == paramTypes[j];
});
var valueStrings: string[] = [];
valueParams.forEach(v => valueStrings.push(v.ParamValue));
this.displayParams.push({ paramType: paramTypes[j], paramValue: valueStrings.join(", ") });
}
}
obtainPatientInformation(): void {
this.createSearchParams();
if (this.searchParams.length > 0) {
var rawResults: angular.IPromise<core.IPatient> = this.searchDataService.performAdvancedSearch(this.searchParams);
var searchControllerInstance: SearchController = this;
this.createDisplayParams();
rawResults.then(
function success(response: any): void {
if (response.data.entry && response.data.entry.length > 0) {
searchControllerInstance.noResults = false;
searchControllerInstance.results = response.data.entry;
for (var index: number = 0; index < searchControllerInstance.results.length; index++) {
var patient: core.IEntry = searchControllerInstance.results[index];
patient.resource.nameString = '';
if (patient.resource.name) {
var familyNameArray: string[] = patient.resource.name[0].family;
for (var familyIndex: number = 0; familyIndex < familyNameArray.length; familyIndex++) {
var familyName: string = familyNameArray[familyIndex];
patient.resource.nameString = patient.resource.nameString + ' ' + familyName.toUpperCase() + ',';
}
var givenNameArray: string[] = patient.resource.name[0].given;
for (var givenIndex: number = 0; givenIndex < givenNameArray.length; givenIndex++) {
var givenName: string = givenNameArray[givenIndex];
patient.resource.nameString = patient.resource.nameString + ' ' + givenName;
}
}
var identifiers: core.IIdentifier[] = patient.resource.identifier;
for (var indentifierIndex: number = 0; indentifierIndex < identifiers.length; indentifierIndex++) {
var identifier: core.IIdentifier = identifiers[indentifierIndex];
if (identifier.system) {
if (identifier.system === 'nhsNumber') {
patient.resource.nhsNumber = identifier.value;
}
if (identifier.system === 'hospitalNumber') {
patient.resource.hospitalNumber = identifier.value;
}
}
}
}
} else {
searchControllerInstance.noResults = true;
searchControllerInstance.results = null;
}
});
}
this.searchClicked = true;
this.checkSearch();
}
checkSearch(): void {
var resultSectionElements: angular.IAugmentedJQuery = angular.element('[id*="resultSection"]');
var advanceSearchSectionElements: angular.IAugmentedJQuery = angular.element('[id*="advanceSearchSection"]');
if (this.searchClicked) {
resultSectionElements.removeClass('ng-hide');
advanceSearchSectionElements.removeClass('ng-show');
advanceSearchSectionElements.addClass('ng-hide');
} else {
resultSectionElements.addClass('ng-hide');
advanceSearchSectionElements.removeClass('ng-hide');
advanceSearchSectionElements.addClass('ng-show');
}
}
returnToSearch(): void {
this.searchClicked = false;
this.searchParams.splice(0,this.searchParams.length);
this.displayParams.splice(0,this.displayParams.length);
this.checkSearch();
}