C# MVC5 BulkData Insert doesn't work on partial view - javascript

I have a problem with inserting bulk data from partial view in MVC5. It works completely fine when its not a partial view. I am using this example: http://www.dotnetawesome.com/2014/08/how-to-insert-multiple-record-to-database-at-a-time-aspnet-mvc4.html
This is the original code from the controller:
public ActionResult BulkData()
{
// This is only for show by default one row for insert data to the database
List<ContactInfo> ci = new List<ContactInfo> {new ContactInfo{ ID = 0, ContactName = "", ContactNo=""} };
return View(ci);
}
I change it to(because I want to use the functionality in bootrap modal popup):
public ActionResult BulkData()
{
// This is only for show by default one row for insert data to the database
List<ContactInfo> ci = new List<ContactInfo> {new ContactInfo{ ID = 0, ContactName = "", ContactNo=""} };
return PartialView(ci);
}
After changes it doesn't work. I can't understand why. I also added all scripts from layout to partial view, but it also didn't help. This is the code from the view:
#model List<MVCBulkInsert.ContactInfo>
#{
ViewBag.Title = "Insert Bulk Data";
}
<style>
th {
text-align:left;
}
td {
padding:5px;
}
</style>
<div style="width:700px; padding:5px; background-color:white;">
#using (Html.BeginForm("BulkData","Save", FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
if (ViewBag.Message != null)
{
<div style="border:solid 1px green">
#ViewBag.Message
</div>
}
<div>Add New</div>
<table id="dataTable" border="0" cellpadding="0" cellspacing="0">
<tr>
<th>Contact Name</th>
<th>Contact No</th>
<th></th>
</tr>
#if (Model != null && Model.Count > 0)
{
int j = 0;
foreach (var i in Model)
{
<tr style="border:1px solid black">
<td>#Html.TextBoxFor(a=>a[j].ContactName)</td>
<td>#Html.TextBoxFor(a=>a[j].ContactNo)</td>
<td>
#if (j > 0)
{
Remove
}
</td>
</tr>
j++;
}
}
</table>
<input type="submit" value="Save Bulk Data" />
}
</div>
#* Here I will add Jquery Code for validation / dynamically add new rows / Remove rows etc *#
#section Scripts{
#Scripts.Render("~/bundles/jqueryval")
<script language="javascript">
$(document).ready(function () {
//1. Add new row
$("#addNew").click(function (e) {
e.preventDefault();
var $tableBody = $("#dataTable");
var $trLast = $tableBody.find("tr:last");
var $trNew = $trLast.clone();
var suffix = $trNew.find(':input:first').attr('name').match(/\d+/);
$trNew.find("td:last").html('Remove');
$.each($trNew.find(':input'), function (i, val) {
// Replaced Name
var oldN = $(this).attr('name');
var newN = oldN.replace('[' + suffix + ']', '[' + (parseInt(suffix) + 1) + ']');
$(this).attr('name', newN);
//Replaced value
var type = $(this).attr('type');
if (type.toLowerCase() == "text") {
$(this).attr('value', '');
}
// If you have another Type then replace with default value
$(this).removeClass("input-validation-error");
});
$trLast.after($trNew);
// Re-assign Validation
var form = $("form")
.removeData("validator")
.removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse(form);
});
// 2. Remove
$('a.remove').live("click", function (e) {
e.preventDefault();
$(this).parent().parent().remove();
});
});
</script>
}
Where can be the problem?

The problem was that partial views don't recognize scripts sections.

Related

ASP.Net MVC passing data from script to new view

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

How can i clone or add multiple ck editor on page

I want multiple textarea(ck editor) where user can input multiple data in it , i tried various function and methods of jquery like clone() and appendTo but the problem is they are cloning the textarea but ckeditor is not working, after cloning the textarea i am unable to wrote anything in it
Please help me with it.
This is what i tried
test1
http://jsfiddle.net/FADxv/793/
test2
http://jsfiddle.net/kbqjnecx/3/
Thanks
Add an id to each new textarea and manually initialize the editor using
CKEditor.replace(id [,config])
Something like:
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
var editorId = 'editor_' + x;
$(wrapper).append('<div> <textarea id="'+editorId+'" class="ckeditor" name="ck[]"></textarea>Remove</div>'); //add input box
CKEDITOR.replace(editorId, { height: 200 });
}
});
DEMO
Check this for cloning ckeditor.
Check this fiddle : http://jsfiddle.net/manektech/47htysb5/
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://cdn.ckeditor.com/4.5.4/standard/ckeditor.js"></script>
</head>
<body>
<div class="row hide_mail_id_domain">
<div class="col-sm-12">
<table class="table">
<thead>
<tr>
<th>Option</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<textarea class="ckeditor" required="" name="question_option_1" ></textarea>
</td>
<td></td>
</tr>
</tbody>
</table>
Add More
</div>
</div>
<script>
var REMOVE = '';
var i=1;
$(document).ready(function () {
$('.add_more').click(function () {
var oneplus=i+1;
var tr_object = $('tbody').find('tr:first').clone();
// getting and renaming existing textarea by name.
$(tr_object).find('textarea[name="question_option_1"]').attr("name", "question_option_"+oneplus+"");
$(tr_object).find('input').val('');
$(tr_object).find('td:last').html('Remove');
$('tbody').append(tr_object);
//replace code
CKEDITOR.replace("question_option_"+oneplus+"");
// when i were clicking on add more during my testing , then extra cke-editor id also appending to DOM. so for removing other then first
// included below code
$('#cke_question_option_1').each(function() {
var $ids = $('[id=' + this.id + ']');
if ($ids.length > 1) {
$ids.not(':first').remove();
}
});
i=i+1;
oneplus++;
});
$(document).on('click', '.remove_more', function () {
var id = $(this).closest('tr').find('.id').val();
if (id != '') {
if (REMOVE != '') {
REMOVE = REMOVE + ',' + id;
} else {
REMOVE = id;
}
$('#id').val(REMOVE);
}
$(this).closest('tr').remove();
});
});
</script>
</body>
</html>

ASP.NET MVC -- Remove From Shopping Cart

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"
})

jQuery - get next element inside checkbox each

I have a table with following columns: checkbox, text, text, ...
For every selected checkbox I need to get the 2nd text value and test if contains some value.
My code so far
$('input:checkbox').each(function () {
var current = $(this);
if (current.is(':checked')) {
var txt = current.next('.inf-name').text();
if (txt.contains(inf) { ... }
}
});
razor code:
<table class="table table-bordered table-modified">
<thead>
<tr>
<th></th>
<th>State</th>
<th>Lookup Type</th>
<th>Plates</th>
<th>Notices</th>
</tr>
</thead>
<tbody>
#Html.HiddenFor(p => p.OrgUnitID, new { #Value = orgUnitId })
#for(var ind = 0; ind < records.Count(); ++ind)
{
var r = records[ind];
var i = ind;
#Html.HiddenFor(p => p.Comp[i].State, new { #Value = #r.State })
<tr>
<td>#Html.CheckBoxFor(p => p.Comp[i].Checked)</td>
<td>#r.State</td>
#if (dict.ContainsKey(r.State))
{ <td class="inf-name">#dict[r.State].ToString()</td> }
else
{ <td class="inf-name"></td> }
<td>#Html.ActionLink(#r.Plates.ToString(CultureInfo.InvariantCulture), "Plates", new { controller = "Lookup", state = #r.State})</td>
<td>#Html.ActionLink(#r.Notices.ToString(CultureInfo.InvariantCulture), "Plates", new { controller = "Lookup" }, new { state = #r.State })</td>
</tr>
}
</tbody>
</table>
where inf-name is the class on 2nd element. I can't get it done. Anyone know a solution?
using next() will get the direct sibling , you need to get parent for check box which is a <td> find the next next sibling using nextAll().eq(1) , get the text inside the that sibling using .text()
Edit :
if you want your target using classes ( provided classes will never change later ) , then just change your code to be :
$('input:checkbox').each(function () {
var current = $(this);
if (current.is(':checked')) {
var txt = current.next('.inf-name').eq(1).text();
if (txt.contains(inf) { ... }
}
});
var currentRows = $('.table tbody tr');
$.each(currentRows, function () {
$(this).find(':checkbox').each(function () {
if ($(this).is(':checked')) {
console.log($(currentRows).eq(1).val());
}
});
});

Javascript value not beeing extracted from the #html.TextBoxFor in a view

I will like to request your help to debug my Jquery which seems not to pick-up my new count for the quantity.
I am in my application and I added a product,
I changed the quantity of the item from 1 to 3. I clicked the refresh button.
I was expecting the total will be changed (total X 3) instead of (total X 1)
I think the problem is coming from the cartCount variable. this variable doesn't seems
to get the new count of the #html.TextBoxFor field from the view.
I got an error with the javascript RefreshQuantity :
In Chrome Pf12, in the header tab
I can see
header tab
id:320
cartCount:0
The id 320 is the corresponding id in the Panier table.
Preview tab
{Message: Error occured or invalid input...,CartTotal:-1, ItemCount:-1, DeleteId:210}
CartCount: -1
CartTotal: -1
DeleteId: 320
ItemCount: -1
Message: "Error occurred or invalid input..."
Response Tab
{"Message":"Error occurred or invalid
input...","CartTotal":-1,"CartCount":-1,"ItemCount":-1,"DeleteId":320}
Index.cshtml
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Shopping Cart";
}
#using (Html.BeginForm())
{
<h3>
<em>Visualisation </em> du panier:
#if (TempData["err_message"] != null)
{
#TempData["err_message"]
}
</h3>
<script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.RemoveLink').click(function () {
$.ajax({
url: '#Url.Action("RemoveFromCart","Panier")',
data: { id: $(this).data('id') },
type: 'POST',
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).remove();
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
$.get('#Url.Action("CartSummary", "Panier")');
$('#content').html(result);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
return false;
});
});
$(function () {
$(".RefreshQuantity").click(function () {
// Get the id from the link
var recordToUpdate = $(this).attr("data-id");
var countToUpdate = 0;
if ($("#" + $(this).attr("id")).val() !== '') {
countToUpdate = $("#" + $(this).attr("id")).val();
}
if (recordToUpdate != '') {
// Perform the ajax post
$.post("/Panier/UpdateCartCount", { "id": recordToUpdate, "cartCount":
countToUpdate },
function (data) {
// Successful requests get here
// Update the page elements
if (data.ItemCount == 0) {
$('#row-' + data. DeleteId).fadeOut('slow');
}
$('#update-message').text(htmlDecode(data.Message));
$('#cart-total').text(data.CartTotal);
$('#cart-status').text('Cart (' + data.CartCount + ')');
//Only process the callback data when no server error occurs
if (data.ItemCount != -1) {
$('#cart-total').text(data.CartTotal);
$('#cart-status').text('Cart (' + data.CartCount + ')');
}
}
);
}
});
});
$(function () {
if (typeof String.prototype.trim !== 'function') {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
}
}
});
function clearUpdateMessage() {
// Reset update-message area
$('#update-message').text('');
}
function htmlDecode(value) {
if (value) {
return $('<div />').html(value).text();
}
else {
return '';
}
}
</script>
<div>
#for (int i = 0; i < Model.CartItems.Count; i++)
{
<p>
#Html.ValidationMessageFor(model => model.CartItems[i].Quantite)
</p>
}
</div>
<div id="update-message">
</div>
<div id="content">
#if (Model.CartTotal != 0)
{
<p class="button">
#Html.ActionLink("Paiement >>", "AddressAndPayment", "Checkout")
</p>
<p class="NouvelAjout">
#Html.ActionLink("Ajouter un autre article >>", "Magasin", "Home")
</p>
}
<table>
<tr>
<th>
Produit
</th>
<th>
Prix (unitaire)
</th>
<th>
Quantite
</th>
<th></th>
</tr>
#{int ix = 0;}
#foreach (var item in Model.CartItems)
{
<tr id="row-#item.ProduitId">
<td>
#Html.ActionLink(item.Produit.Description, "Details", "Produit", new { id =
item.ProduitId }, null)
</td>
<td>
#item.Produit.Prix
</td>
<td>
#Html.TextBoxFor(model => model.CartItems[ix].Quantite,
new {style = "width:30px; text-align:right;",
onkeyup = "clearUpdateMessage();",
onchange = "clearUpdateMessage();"
})
</td>
<td>
<a href="#" class="RefreshQuantity" data-id="#item.PanierId"
id="CartItems_#(ix)__Count">Refresh quantity</a> | />a
</td>
<td>
<a href="#" class="RemoveLink" data-id="#item.PanierId"> Enlever du panier
>> </a>
</td>
</tr>
ix++;
}
<tr>
<td>
Total
</td>
<td></td>
<td></td>
<td id="cart-total">
#Model.CartTotal
</td>
</tr>
</table>
</div>
}
Do we have anyway to debug the javascript from Visual Studio? I saw a post which is stating it was a problem with Visual studio ref.: Visual Studio 2013 can't debug javascript in cshtml
ShoppingCart.cs
public int UpdateCartCount(int id, int cartCount)
{
// Get the cart
var cartItem = db.Paniers.Single(
cart => cart.CartId == ShoppingCartId
&& cart.PanierId == id);
int itemCount = 0;
if (cartItem != null)
{
if (cartCount > 0) <=== cartCount is always 0 it should contains the new value
added from the view.
{
cartItem.Quantite = cartCount;
itemCount = cartItem.Quantite;
}
else
{
db.Paniers.Remove(cartItem);
}
// Save changes
db.SaveChanges();
}
return itemCount;
}
I need to know how to extract the new value added by the user in the screen from the view field
#Html.TextBoxFor(model => model.CartItems[ix].Quantite,
new {style = "width:30px; text-align:right;",
onkeyup = "clearUpdateMessage();",
onchange = "clearUpdateMessage();"
})
Change to textbox:
#Html.TextBoxFor(model => model.CartItems[ix].Quantite,
new {style = "width:30px; text-align:right;",
onkeyup = "clearUpdateMessage();",
onchange = "clearUpdateMessage();",
#class="new-count"
})
Change to script:
$(".RefreshQuantity").click(function () {
// Get the id from the link
var recordToUpdate = $(this).attr("data-id");
var countToUpdate = $(this)
.closest('tr')
.find('.new-count').val();
The error was on the Index.cshtml with the var id="CartItems_#(ix)__Count"
old view
<td>
<a href="#" class="RefreshQuantity" data-id="#item.PanierId"
id="CartItems_#(ix)__Count">Refresh quantity</a> | />a
</td>
Modified
<td>
<a href="#" class="RefreshQuantity" data-id="#item.PanierId"
id="CartItems_#(ix)__Quantite">Refresh quantity</a> | />a
</td>

Categories

Resources