Deleting row from a DataTable in asp.net - c#

I'm trying to get my delete button from a modal popup to delete a row from my local database which is in Visual Studio.
I'm not quite sure how to do this. I'm new to this, so if I'll have to add some data. Please inform me.
This is the Controller:
using MusicBox.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
namespace MusicBox.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
//Tab Box
//[HttpGet]
public ActionResult Box()
{
return View();
}
////Dobivanje liste unutar gumba
[HttpGet]
public ActionResult Create()
{
var viewModel = new MusicViewModel();
var genres = new List<Genre>();
var genreList = new List<SelectListItem>();
using (var db = new ApplicationDbContext())
{
genres = db.Genres.ToList();
}
foreach (var genre in genres)
{
genreList.Add(new SelectListItem() { Value = genre.Id.ToString(), Text = genre.Type });
}
viewModel.Genres = genreList;
return View(viewModel);
}
[HttpPost]
public ActionResult Create(MusicViewModel model)
{
//Ovo je validation message
//if (!ModelState.IsValid)
//{
// var viewModel = new MusicViewModel();
// var genres = new List<Genre>();
// var genreList = new List<SelectListItem>();
// using (var db = new ApplicationDbContext())
// {
// genres = db.Genres.ToList();
// }
// foreach (var genre in genres)
// {
// genreList.Add(new SelectListItem() { Value = genre.Id.ToString(), Text = genre.Type });
// }
// viewModel.Genres = genreList;
// return View(viewModel);
//}
var song = new Song
{
GenreId = model.GenreId,
Performer = model.Performer,
Title = model.Title,
Year = model.Year,
YoutubeLink = model.YoutubeLink
};
using (ApplicationDbContext db = new ApplicationDbContext())
{
try
{
db.Songs.Add(song);
db.SaveChanges();
}
catch (Exception e) { }
}
//ovdje ide dodavanje u bazu
return RedirectToAction("List");
}
public ActionResult List()
{
var songs = new List<Song>();
var songList = new List<SongListViewModel>();
try
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
songs = db.Songs.ToList();
foreach (var song in songs)
{
songList.Add(new SongListViewModel
{
Performer = song.Performer,
Song = song.Title,
Genre = song.Genre.Type,
Year = song.Year,
Link = song.YoutubeLink,
Id = song.Id
});
}
}
}
catch (Exception)
{
throw;
}
return View(songList);
}
public ActionResult Edit()
{
return View("Create");
}
}
}
This is the HTML:
#using System.Activities.Expressions
#using System.Web.Mvc.Html
#using MusicBox.Models
#model IEnumerable<SongListViewModel>
#{
ViewBag.Title = "Popis";
}
<h2>Popis pjesama</h2>
<table class="table table-bordered">
<thead class="thead">
<tr>
<th>
Izvođač
</th>
<th>
Pjesma
</th>
<th>
Žanr
</th>
<th>
Godina
</th>
<th>
Youtube Link
</th>
<th>
</th>
<th>
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#item.Performer</td>
<td>#item.Song</td>
<td>#item.Genre</td>
<td>#item.Year</td>
<td>Link</td>
<td>
#Html.ActionLink("Edit", "Edit", new {id = item.Id})
</td>
<td>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#confirmSongDelete" data-songId="#item.Id">
Briši
</button>
</td>
</tr>
}
</tbody>
</table>
<div class="modal fade" id="confirmSongDelete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Brisanje pjesme</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Da li sigurno želite izbrisati?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Odustani</button>
<button type="button" class="btn btn-primary">Obriši</button>
</div>
</div>
</div>
</div>

It would be something like that:-
Javascript
<script>
$(document).ready(function () {
$('#confirmSongDelete').on('show.bs.modal', function (e) {
var id = $(e.relatedTarget).attr('id');
$("#btnConfirm").attr("id", id);
});
})
function DeleteSong(Id) {
$("div[class='Success']").empty();
$("div[class='failure']").empty();
//call action method
$("#confirmSongDelete").modal("hide");
$.ajax({
url: "#Url.Action("DeleteSong", "HomeController")",
data: { id: Id },
success: function (response) {
if (response != null && response == "True") {
$("#spnSuccessMsg").css("display", "block");
$("#myModalOk").modal('show');
} else {
$("#spnErrorMsg").css("display", "block");
$("#myModalOk").modal('show');
}
window.location.href = window.location.href;
}
});
}
</script>
View
#using System.Activities.Expressions
#using System.Web.Mvc.Html
#using MusicBox.Models
#model IEnumerable<SongListViewModel>
#{
ViewBag.Title = "Popis";
}
<h2>Popis pjesama</h2>
<table class="table table-bordered">
<thead class="thead">
<tr>
<th>
Izvođač
</th>
<th>
Pjesma
</th>
<th>
Žanr
</th>
<th>
Godina
</th>
<th>
Youtube Link
</th>
<th>
</th>
<th>
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#item.Performer</td>
<td>#item.Song</td>
<td>#item.Genre</td>
<td>#item.Year</td>
<td>Link</td>
<td>
#Html.ActionLink("Edit", "Edit", new {id = item.Id})
</td>
<td>
<button id="#item.Id" type="button" class="btn btn-primary" data-toggle="modal" data-target="#confirmSongDelete" data-songId="#item.Id">
Briši
</button>
</td>
</tr>
}
</tbody>
</table>
<div class="modal fade" id="confirmSongDelete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Brisanje pjesme</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Da li sigurno želite izbrisati?</p>
</div>
<div class="modal-footer">
<button id="btnConfirm" type="button" class="btn btn-secondary" data-dismiss="modal" onclick="DeleteSong(id);">Odustani</button>
<button type="button" class="btn btn-primary">Obriši</button>
</div>
</div>
</div>
</div>
Controller
public bool DeleteSong()
{
int _deleteResult=0;
string _songId = Request.QueryString["id"];
using (ApplicationDbContext db = new ApplicationDbContext())
{
Song songsMaster = _context.Songs.Single(m => m.SongId == _songId);
_context.Songs.Remove(songsMaster);
_deleteResult= _context.SaveChanges();
}
if(_deleteResult>0)
{
return true;
}
else
{
return false;
}
}

Related

Return List grouped by two properties using linq ASP.NET MVC

So I have this Table with class Report:
Based on the ProductId and ReportType I want to create a LINQ expression that returns a List<ReportInnerResponse>, where ReportInnerResponse contains the following:
public class ReportInnerResponse
{
public int Id { get; set; }
public ReportType ReportType { get; set; }
public int ReportCount { get; set; }
}
So my final result would be something like this:
Here is my current code, but it does not work properly:
public ActionResult GetReportsById(int id)
{
var reports = DbContext.Reports.GroupBy(x => new {x.ProductId, x.ReportType}).Select(g => g.FirstOrDefault()).Where(x => x.ProductId == id).Select(r =>
new Models.Response.ReportInnerResponse
{
Id = r.Id,
ReportType = r.ReportType,
ReportCount = DbContext.Reports.Where(x => x.ReportType == r.ReportType && x.ProductId == id).Count()
}).ToList();
return PartialView("_ProductReportDetails", reports);
}
Main View:
#model IEnumerable<Finder.Models.Response.AdminReportResponse>
#{
ViewBag.Title = "Report Panel | Finder";
}
<h2>Report Panel</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Image)
</th>
<th>
#Html.DisplayNameFor(model => model.Title)
</th>
<th>
Seller
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th>
Report Info
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<img src="#item.Image" height="100px" width="100px" style="object-fit: contain" />
</td>
<td>
#Html.DisplayFor(modelItem => item.Title)
</td>
<td>
#Html.DisplayFor(modelItem => item.FullName)
</td>
<td>
#{
var price = item.Price.ToString("C");
}
#price
</td>
<td>
#if (item.ReportCount >= 1)
{
<span>#item.ReportCount</span>
#Html.Action("GetReportsById", new { id = item.Id })
}
</td>
</tr>
}
</table>
Partial View:
#model List<Finder.Models.Response.ReportInnerResponse>
<!-- Button trigger modal -->
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#exampleModalCenter">
<i class="fa-solid fa-flag" style="margin-right:10px;"></i> See Reports
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document" style="width: 100%">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Report Menu</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#foreach (var item in Model)
{
<p><span>#item.ReportCount</span>#item.ReportType</p>
}
</div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
Any help would be appreciated.
Id property on Models.Response.ReportInnerResponse does not make much sense, TBH, since it represents grouping result (or it should be named ProductId). Remove it and try rewriting your query this way:
var reports = DbContext.Reports
.Where(x => x.ProductId == id) // filter out not needed data before grouping
.GroupBy(x => x.ReportType)
.Select(g => new Models.Response.ReportInnerResponse
{
ReportType = g.Key,
ReportCount = g.Count()
})
.ToList();

Failed to create new data into the database using the popup form

I was trying to create a popup system to create new data into the database. when I click"Create" in my index view then I find a popup form.but when I click "Save" for data save then it does not work anything. suddenly it works and saves the data into the database. but it happened just one time. but I don't understand why it's not working smoothly.
Here is my code:
Model
namespace Practise.Models
{
public class Category
{
public int Id { get; set; }
public string CategoryName { get; set; }
}
}
Controller:
namespace Practise.Controllers
{
public class CategoryController : Controller
{
private ApplicationDbContext _db;
public CategoryController(ApplicationDbContext db) //input parameter
{
_db = db;
}
public IActionResult Index()
{
return View(_db.Category.ToList());
}
[HttpGet]
public IActionResult Create()
{
Category ca = new Category();
return PartialView("_CreatePartial", ca);
//return View();
}
[HttpPost]
public IActionResult Create(Category ca)
{
_db.Category.Add(ca);
_db.SaveChanges();
return PartialView("_CreatePartial", ca);
}
}
}
Index.cshtml
#model IEnumerable<Practise.Models.Category>
#{
ViewData["Title"] = "Index";
}
<div id="PlaceHolderHere"></div>
<button type="button" class="btn btn-primary" data-toggle="ajax-model" data-target="#addEmployee" data-url="#Url.Action("Create")">Create</button>
</br></br>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Id)
</th>
<th>
#Html.DisplayNameFor(model => model.CategoryName)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.CategoryName)
</td>
<td>
<partial name="_ButtonPartial" model="#item.Id" />
</td>
</tr>
}
</tbody>
</table>
#section scripts{
<script src="//cdn.jsdelivr.net/npm/alertifyjs#1.13.1/build/alertify.min.js"></script>
<script type="text/javascript">
$(function(){
var save = '#TempData["save"]'
if (save!= null) {
alertify.success(save);
}
})
</script>
}
_CreatePartial view:
#model Category
<div class="modal fade" id="#addEmployee">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="#addEmployeeLabel">Add Category</h4>
<button type="button" class="close" data-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form action="Create">
<div class="form-group">
<label asp-for="CategoryName"> </label>
<input asp-for="CategoryName" class="form-control" />
<span asp-validation-for="CategoryName" class="text-danger"></span>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-save="modal">Save</button>
</div>
</div>
</div>
</div>
JS(site.js)
$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-toggle="ajax-model"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
})
})
PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function (data) {
PlaceHolderElement.find('.modal').modal('hide');
})
})
})
My Output:
when I press the save button I want it to save the data to DB.but it does not work.
I have to change something like that for save data:
public IActionResult Create()
{
//Category ca = new Category();
//return PartialView("_CreatePartial", ca);
return View();
}
[HttpPost]
public IActionResult Create(Category ca)
{
_db.Category.Add(ca);
_db.SaveChanges();
return RedirectToAction("Index");
}
Create View:
#model Practise.Models.Category
#{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<div class="modal fade" id="#addEmployee">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="#addEmployeeLabel">Add Category</h4>
<button type="button" class="close" data-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form asp-action="Create" method="post">
<div class="form-group">
<label asp-for="CategoryName"> </label>
<input asp-for="CategoryName" class="form-control" />
<span asp-validation-for="CategoryName" class="text-danger"></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
#*<button type="button" class="btn btn-primary" data-save="modal">Save</button>*#
<input type="submit" class="btn btn-primary" value="Submit"/>
</div>
</form>
</div>
</div>
</div>
</div>
then successfully will save data.

update session data from ViewModel

here I updated my quantity. how I will use or inject this updated quantity?
[HttpGet]
public ActionResult Details(int? id)
{
ViewBag.product = _db.Spray.ToList();
if (id == null)
{
return NotFound();
}
var hi = _db.Spray.Include(c => c.ProductTypes).FirstOrDefault(c => c.Id == id);
ProductVm product = new ProductVm
{
Name = hi.Name,
Id = hi.Id,
Image=hi.Image,
Image1=hi.Image1,
Quantity = hi.Quantity,
Price = hi.Price,
};
if (product == null)
{
return NotFound();
}
return View(product);
}
[HttpPost]
[ActionName("Details")]
public async Task <IActionResult> ProductDetails(ProductVm pb)
{
List<Spray> sprays = new List<Spray>();
//if (id == null)
//{
// return NotFound();
//}
//var yes = _db.Spray.Include(c => c.ProductTypes).FirstOrDefault(c => c.Id == id);
ProductVm product = new ProductVm()
{
Name = pb.Name,
Id = pb.Id,
Image = pb.Image,
Image1=pb.Image1,
Quantity = pb.Quantity,
Price = pb.Price,
};
if (product == null)
{
return NotFound();
}
sprays = HttpContext.Session.Get<List<Spray>>("sprays");
if (sprays == null)
{
sprays = new List<Spray>();
}
sprays.Add(product);
HttpContext.Session.Set("sprays", sprays);
return RedirectToAction(nameof(Index));
}
[HttpGet]
public IActionResult Cart()
{
List<Spray> sprays = HttpContext.Session.Get<List<Spray>>("sprays");
if (sprays == null)
{
sprays = new List<Spray>();
}
return View(sprays);
}
#model List<Spray>
#{
ViewData["Title"] = "Cart";
}
<div>
<div class="row">
<div class="col-6">
<table class="table table-bordered">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Quantity Update</th>
<th>Total</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<img src="~/#item.Image" width="200px" height="150px" />
</td>
<td>#item.Name</td>
<td>#item.Quantity</td>
<td>#item.Price</td>
<td>
<input type="number" asp-for="#item.Quantity" min="0" max="1000" />
</td>
<td>#(item.Price * item.Quantity)</td>
<td>
<a asp-area="Customer" asp-action="Remove" asp-controller="LaptopShow" asp-route-id="#item.Id" class="btn btn-danger">
<i class="fas fa-trash"></i>
</a>
</td>
</tr>
}
</tbody>
</table>
</div>
<div class="col-6">
<div class="text-right">
<h3>Total Amount</h3>
<h3>Grand Total : #Model.Sum(c => c.Price * c.Quantity)</h3>
<a asp-area="Customer" asp-action="Checkout" asp-controller="Order" class="btn btn-info">Process To CheckOut</a>
</div>
</div>
<div>
<a asp-action="Index" asp-controller="SprayShow" class="btn btn-primary">Back To Home</a>
</div>
</div>
</div>
#*<div>
#Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
<a asp-action="Index">Back to List</a>
</div>*#
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function () {
$("input[name='item.Quantity']").change(function () {
//get the new quantity
var newquantity = parseInt($(this).val());
//update the original quantity value
$(this).closest("tr").find("td")[2].innerHTML = newquantity;
//get the price
var price = parseFloat($(this).closest("tr").find("td")[3].innerHTML);
//calculate the total
$(this).closest("tr").find("td")[5].innerHTML = newquantity * price;
//calcule the Grand Total
var grandtotal = 0;
$("tbody").find("tr").each(function (index, item) {
var value = parseFloat($(item).find("td")[5].innerHTML);
grandtotal += value;
});
$(".text-right h3:last").html("Grand Total : " + grandtotal.toString());
});
});
</script>
above code, I change quantity increase and decrease for calculating.but this update value session data could not pick. for that, I am found a problem here to process to checkout problem. I can not found actual quantity data which I updated cart.cshtml.
here my output the updated the quantity using jquery
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HuddsonBay.Data;
using HuddsonBay.Models;
using HuddsonBay.Utility;
using Microsoft.AspNetCore.Mvc;
namespace HuddsonBay.Areas.Customer.Controllers
{
[Area("Customer")]
public class OrderController : Controller
{
private ApplicationDbContext _db;
public OrderController(ApplicationDbContext db)
{
_db = db;
}
[HttpGet]
public IActionResult Checkout()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Checkout(Order anOrder)
{
//session theke data peck
List<Spray> sprays = HttpContext.Session.Get<List<Spray>>("sprays");
if (sprays != null)
{
for each (var mobile in sprays)
{
OrderDetails orderDetails1 = new OrderDetails();
orderDetails1.ProductId = mobile.Id;
anOrder.OrderDetails.Add(orderDetails1);
}
}
anOrder.OrderNo = GetOrderNo();
_db.Orders.Add(anOrder);
await _db.SaveChangesAsync();
HttpContext.Session.Set("sprays", new List<Spray>());
return RedirectToAction(nameof(Checkout));
}
public String GetOrderNo() //for count order number
{
int rowCount = _db.Orders.ToList().Count() + 1;
return rowCount.ToString("000");
}
}
}
above view, the list of item session data can not pick my updated quantity. how I solved this problem. I am facing problem in order of the value of the quantity.
I am beginner, please anyone help.
Here is a demo to show how to pass List to controller with ajax:
Spray:
public class Spray
{
public int Id { get; set; }
public string Image { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public int Price { get; set; }
public int Total { get; set; }
}
Controller:
[HttpGet]
public IActionResult Cart()
{
List < Spray > sprays= new List<Spray> { new Spray { Id = 1, Name = "product1", Price = 10, Quantity = 1, Total = 1,Image="image1.png" }, new Spray { Id = 2, Name = "product2", Price = 20, Quantity = 1, Total = 20,Image="Image2.png" } };
return View(sprays);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SendSprays([FromBody]IList<Spray> t) {
return RedirectToAction(nameof(Cart));
}
Cart.cshtml:
<div>
<div class="row">
<div class="col-6">
<table class="table table-bordered" id="myTable">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Quantity Update</th>
<th>Total</th>
<th></th>
<th hidden>Id</th>
<th hidden>ImageValue</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<img src="~/#item.Image" width="200px" height="150px" />
</td>
<td>#item.Name</td>
<td>#item.Quantity</td>
<td>#item.Price</td>
<td>
<input type="number" asp-for="#item.Quantity" min="0" max="1000" />
</td>
<td>#(item.Price * item.Quantity)</td>
<td>
<a asp-area="Customer" asp-action="Remove" asp-controller="LaptopShow" asp-route-id="#item.Id" class="btn btn-danger">
<i class="fas fa-trash"></i>
</a>
</td>
<td hidden>#item.Id</td>
<td hidden>#item.Image</td>
</tr>
}
</tbody>
</table>
</div>
<div class="col-6">
<div class="text-right">
<h3>Total Amount</h3>
<h3>Grand Total : #Model.Sum(c => c.Price * c.Quantity)</h3>
<button onclick="checkout()">Process To CheckOut</button>
#*<a asp-action="Checkout" asp-controller="Test" class="btn btn-info">Process To CheckOut</a>*#
</div>
</div>
<div>
<a asp-action="Index" asp-controller="SprayShow" class="btn btn-primary">Back To Home</a>
</div>
</div>
</div>
#*<div>
#Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
<a asp-action="Index">Back to List</a>
</div>*#
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function () {
$("input[name='item.Quantity']").change(function () {
//get the new quantity
var newquantity = parseInt($(this).val());
//update the original quantity value
$(this).closest("tr").find("td")[2].innerHTML = newquantity;
//get the price
var price = parseFloat($(this).closest("tr").find("td")[3].innerHTML);
//calculate the total
$(this).closest("tr").find("td")[5].innerHTML = newquantity * price;
//calcule the Grand Total
var grandtotal = 0;
$("tbody").find("tr").each(function (index, item) {
var value = parseFloat($(item).find("td")[5].innerHTML);
grandtotal += value;
});
$(".text-right h3:last").html("Grand Total : " + grandtotal.toString());
});
});
function checkout() {
var oTable = document.getElementById('myTable');
//gets rows of table
var rowLength = oTable.rows.length;
var sprays = new Array();
//loops through rows
for (i = 1; i < rowLength; i++) {
var tempspray = {};
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
//gets amount of cells of current row
var cellLength = oCells.length;
//tempspray.image = oCells.item(j).
tempspray.Name = oCells.item(1).innerHTML;
tempspray.Quantity = parseInt(oCells.item(2).innerHTML);
tempspray.Price = parseInt(oCells.item(3).innerHTML);
tempspray.Total = parseInt(oCells.item(5).innerHTML);
tempspray.Id = parseInt(oCells.item(7).innerHTML);
tempspray.Image = oCells.item(8).innerHTML;
sprays.push(tempspray);
}
var token = $('input[name="__RequestVerificationToken"]').val();
var t = JSON.stringify(sprays);
$.ajax({
type: "POST",
url: '#(Url.Action("SendSprays", "Test"))',
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
data: t,
contentType: "application/json; charset=utf-8"
});
}
</script>
result:

Modal Bootstrap on ASP.NET MVC

I trying to do a responsive async page with Modal bootstrap, it´s things all right, although when a save object on modal form, is did a update, but the return is to a json page:
The Controller Method returns a Json
using CaelumEstoque.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CaelumEstoque.Controllers
{
public class ProdController : Controller
{
public static List<Prod> _listaProdutos = new List<Prod>()
{
new Prod { Codigo=01, Descricao="Produto 1", Preco=10 },
new Prod { Codigo=02, Descricao="Produto 2", Preco=15 },
new Prod { Codigo=03, Descricao="Produto 3", Preco=20 }
};
public ActionResult Index()
{
IList<Prod> lista = _listaProdutos;
return View(lista);
}
public ActionResult Details(int id)
{
var existe = _listaProdutos.Find(x => x.Codigo == id);
ViewBag.Detalhes = existe;
return View("parcial", existe);
}
public ActionResult Edit(int id)
{
var existe = _listaProdutos.Find(x => x.Codigo == id);
return View(existe);
}
public ActionResult ParcialEdit(Prod p)
{
var registro = _listaProdutos.Find(x => x.Codigo == p.Codigo);
registro.Descricao = p.Descricao;
registro.Preco = p.Preco;
return Json(registro);
}
public ActionResult parcial()
{
return View();
}
}
}
My Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CaelumEstoque.Models
{
public class Prod
{
public int Codigo { get; set; }
public string Descricao { get; set; }
public double Preco { get; set; }
}
}
Index View:
#model IEnumerable<CaelumEstoque.Models.Prod>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Codigo)
</th>
<th>
#Html.DisplayNameFor(model => model.Descricao)
</th>
<th>
#Html.DisplayNameFor(model => model.Preco)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr id="prod#(item.Codigo)">
<td>
#Html.DisplayFor(modelItem => item.Codigo)
</td>
<td>
#Html.DisplayFor(modelItem => item.Descricao)
</td>
<td>
#Html.DisplayFor(modelItem => item.Preco)
</td>
<td>
Detalhe
<i class="glyphicon glyphicon-edit"></i>
#*<button class="btn btn-default details" data-id="#item.Codigo"><i class="glyphicon glyphicon-file"></i></button>
<button class="btn btn-danger delete" data-id="#item.Codigo"><i class="glyphicon glyphicon-trash"></i></button>
<button class="btn btn-primary edit" data-id="#item.Codigo"><i class="glyphicon glyphicon-edit"></i></button>*#
</td>
</tr>
}
</table>
<div class="modal" id="modal">
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
$(function () {
$('.details').click(function () { // class name selector
var url = $(this).data('url'); // use data(), not attr()
$("#modal").load(url, function () {
$("#modal").modal("show");
})
});
})
/*
$(".edit").click(function () {
var url = $(this).data('url'); // use data(), not attr()
$("#modal").load(url, function () {
$("#modal").modal("show");
})
})
*/
$("#.edit").click(function () {
$.ajax({
type: "POST",
url: "",
data: $('#modal').serialize(),
success: function (data) {
alert('Registro salvo com sucesso.');
$('#modal').modal('hide');
},
error: function (data) {
alert('Erro ao Salvar Registro.');
}
});
});
</script>
Modal View:
#model CaelumEstoque.Models.Prod
#{
Layout = null;
}
<div class="modal-dialog">
<div class="modal-content">
#using (Ajax.BeginForm("ParcialEdit", "Prod", new AjaxOptions { UpdateTargetId = "Error", InsertionMode = InsertionMode.Replace, OnSuccess = "OnSuccess(data)" }))
{
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Editar produto</h4>
</div>
<div class="modal-body">
<div class="form-horizontal">
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.Codigo, new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.TextBoxFor(model => model.Codigo, new { #class = "form-control", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Codigo)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Descricao, new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.TextBoxFor(model => model.Descricao, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Descricao)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Preco, new { #class = "control-label col-md-3" })
<div class="col-md-9">
#Html.TextBoxFor(model => model.Preco, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Preco)
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="submit" value="Salvar" class="btn btn-primary salvar" />
#*<input type="button" value="Salvar" class="btn btn-primary salvar" data-url="#Url.Action("ParcialEdit", "Prod", new {p = Model })" /> *#
<input type="button" value="Cancelar" class="btn btn-default" data-dismiss="modal" />
</div>
}
</div>
</div>
<script>
</script>
I want to know what is my mistake
Thank you

Update the view from Controller, does not work, when PartialView is added

again i can not update my view:
#model CCM.WebApp.MVC.ViewModels.Workflow.Edit.EditWorkflowViewModel
#Html.TextBoxFor(m => m.Test, new { id = "txtbTest", #class = "form-control" })
<button class="btn btn-success" id="btnOk"><i class="fa fa-floppy-o"></i> Ok</button>
<div id="collapsePanelBody" class="panel-collapse collapse in">
<div class="panel-body" id="partialWorkflowStepList">
#{ Html.RenderPartial("../WorkflowStep/_WorkflowStepList", Model.IndexWorkflowStepViewModel); }
</div>
</div>
Controller Action:
[HttpPost]
public ActionResult Edit(EditWorkflowViewModel viewModel)
{
ModelState.Clear();
//... Code to persist the viewModel Data...
viewModel.Test = "changed";
if (Request.IsAjaxRequest())
return PartialView("_Edit", viewModel);
return View("_Edit", viewModel);
}
the update of the TextBox only works, when i delete the partial in the view-code:
#{ Html.RenderPartial("../WorkflowStep/_WorkflowStepList", Model.IndexWorkflowStepViewModel); }
i don't understand, why it does not update, when i have this partial in my view.
please explain this behaviour and how i can fix that
Edit:
the partial view:
#model CCM.WebApp.MVC.ViewModels.WorkflowStep.Index.IndexWorkflowStepViewModel
#if (Model.SubmitModel != null && Model.SubmitModel.Items != null && Model.SubmitModel.Items.Any())
{
#*#Html.ShowPagerCount(#Model.SubmitModel.Items.ItemStart, #Model.SubmitModel.Items.ItemEnd, #Model.SubmitModel.Items.TotalItemCount)*#
}
<div class="clearfix"></div>
<div style="margin-top: 5px; margin-bottom: 5px; border: 1px solid #ddd;">
<table class="table table-hover table-nobottom table-striped">
<thead>
<tr>
<th>
# <i class="fa fa-fw fa-sort-alpha-asc" data-toggle="tooltip" data-placement="top" title="Sortierung: Schrittnummer (1-9)"></i>
</th>
<th>
</th>
<th>
Beschreibung
</th>
#*<th>
Kategorie
</th>*#
<th class="text-center">
Status
</th>
<th></th>
</tr>
</thead>
<tbody>
#if (Model.SubmitModel != null && Model.SubmitModel.Items != null && Model.SubmitModel.Items.Any())
{
foreach (var item in Model.SubmitModel.Items)
{
<tr>
<td>
#item.StepNo
</td>
<td style="width: 80px;white-space:normal;word-wrap: break-word;" align="center">
<img src="#Url.Content(item.StepTypeImageUrl)" alt="IMAGES" title="#item.DisplayText.ToString()" />
</td>
<td style="max-width: 400px;white-space:normal;word-wrap: break-word;padding: 2px;">
<div>#Html.Raw(HttpUtility.HtmlDecode(#item.Description))</div>
</td>
#*<td>
#item.Category
</td>*#
<td class="text-center">
#if (item.IsActive)
{
<i class="fa fa-check" style="color: green;"></i>
}
else
{
<i class="fa fa-ban" style="color: red;"></i>
}
</td>
<td>
<div class="float-left">
<span class="glyphicon glyphicon-edit big" data-toggle="tooltip" title="Datensatz ändern"></span>
</div>
<div class="float-left">
<span class="glyphicon glyphicon-trash big" data-toggle="tooltip" title="Datensatz löschen"></span>
</div>
<div class="float-left" style="display:#(item.StepNo == Model.SubmitModel.Items.Count ? "none;" : "inline;")">
<span class="glyphicon glyphicon-arrow-down big" data-toggle="tooltip" title="Position nach unten verschieben"></span>
</div>
<div class="float-left" style="display:#(item.StepNo == 1 ? "none;" : "inline;")">
<span class="glyphicon glyphicon-arrow-up big" data-toggle="tooltip" title="Position nach oben verschieben"></span>
</div>
</td>
</tr>
}
}
else
{
<tr><td colspan="4">Keine Daten vorhanden</td></tr>
}
</tbody>
</table>
</div>
EditWorkflowViewModel:
public class EditWorkflowViewModel : CreateWorkflowViewModel
{
public string Test { get; set; }
public EditWorkflowViewModel()
{
SubmitModel = new EditWorkflowSubmitModel();
}
}
public class CreateWorkflowViewModel : BaseViewModel
{
#region Properties
public CreateWorkflowSubmitModel SubmitModel { get; set; }
[Display(Name = "Farbe")]
public List<SelectListItem> AvailableColors { get; set; }
public IndexWorkflowStepViewModel IndexWorkflowStepViewModel { get; set; }
#endregion
public CreateWorkflowViewModel()
{
SubmitModel = new CreateWorkflowSubmitModel();
}
}
IndexWorkflowStepViewModel:
public class IndexWorkflowStepViewModel : BaseViewModel
{
#region Properties
public IndexWorkflowStepSubmitModel SubmitModel { get; set; }
public string WorkflowName { get; set; }
#endregion
#region Constructor
public IndexWorkflowStepViewModel()
{
SubmitModel = new IndexWorkflowStepSubmitModel();
}
#endregion
}

Categories

Resources