mvc Get a value of element in different cshtml with jquery - asp.net-mvc

I have a page ("mypage.cshtml") and two partial view page ( partial1.cshtml, partial2.cshtml )
when Im in mypage click a button and display a modal which call partial1 with #Html.Partial("patial1") in a modal(bootstrap modal). it consist of html. when I a click a button on this modal it calls another modal consist of partial2..
Here is the issue; When I load the page begining (in mypage ) I need to get the value of checkbox that standing in second modal, that is partial2.
During I view this modal I can get this value with this:
$("input[type='checkbox'][id='4']").val();
it gives me the value which I expect but at the begining(in mypage.cshtml) this returns "undefined" :S
I couldnt understand this stuation both of these modal located in mypage but why I cant get these elements values untill I reach them ?
here is view mypage:
<div id="stack1" class="modal fade" tabindex="-1" data-width="400">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">#Model.Kurulus.TESIS_ADI</h4>
</div>
<div class="modal-body">
<form id="formKaydet" method="post" action="../KurulusBilgileri/KurulusBilgileriniGuncelle">
<div class="row">
<div class="col-md-12">
#Html.Partial("KurulusBilgileriniGuncelle", Model)
</div>
<div class="modal-footer">
<input type="hidden" name="SANAYI_TIPI" id="input_id" />
<input type="hidden" name="SANAYI_TIPI_DIGER" id="input_sanayitipi" />
<button type="button" data-dismiss="modal" class="btn default">Geri</button>
<a class="btn orange" onclick="sanayitipleriKaydet()">Kaydet A</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="stack2" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">#Model.Kurulus.TESIS_ADI</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
#Html.Partial("SanayiTipiSecim", Model.SanayitipiModel)
</div>
</div>
</div>
<div class="modal-footer">
#*<button type="button" data-dismiss="modal" class="btn">Close</button>
<button type="button" class="btn yellow">Ok</button>*#
</div>
</div>
</div>
</div>
and my second modal (SanayiTipiSecim)
<table class="table-full-width">
<thead>
<tr>
<th></th>
<th><strong>Sanayici Tipi</strong></th>
<th><strong>Açıklama</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" onclick="javascript:sanayitipiTotextarea(1)" id="1" value="Boya Sanayi">
</td>
<td>
Boya Sanayi
</td>
<td>
Boya üretimi yapan imalathaneler
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" onclick="javascript:sanayitipiTotextarea(2)" id="2" value="Enerji üretimi ve dağıtımı">
</td>
<td>
Enerji üretimi ve dağıtımı
</td>
<td>
Ör. Enerji üretim merkezleri, enerji ara istasyonları vb?
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" id="3" onclick="javascript:sanayitipiTotextarea(3)" value="Elektrik ve Elektronik Mühendisliği">
</td>
<td>
Elektrik ve Elektronik Mühendisliği
</td>
<td>
Elektronik parçaların üretimi vb?
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" id="4" onclick="javascript:sanayitipiTotextarea(4)" value="Genel Mühendislik, imalat ve montaj">
</td>
<td>
Genel Mühendislik, imalat ve montaj
</td>
<td>
Herhangi bir mühendislik aktivitesi, üretim veya montaj vb?
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="SANAYI_TIPI" id="5" onclick="javascript:sanayitipiTotextarea(5)" value="Gıda ve içecek">
</td>
<td>
Gıda ve içecek
</td>
<td>
Gıda, alkollü içki vb?
</td>
script blocks in first page:
<script src="~/Scripts/js/kurulusbilgileri.js"></script>
<script>
sanayitipleriKaydet = function () {
debugger
var data = new Object()
data.ISIM = $("input[name='ISIM']").val();
data.ADRES_METIN = $("input[name='ADRES_METIN']").val();
data.TELEFON = $("input[name='TELEFON']").val();
data.FAKS = $("input[name='FAKS']").val();
data.E_POSTA = $("input[name='E_POSTA']").val();
data.SORUMLU_ISIM = $("input[name='SORUMLU_ISIM']").val();
data.SORUMLU_SOYISIM = $("input[name='SORUMLU_SOYISIM']").val();
data.FAALIYET_ALANI = $("input[name='FAALIYET_ALANI']").val();
data.CEVRE_BILGI = $("input[name='CEVRE_BILGI']").val();
data.BELEDIYE_MUCAVIR_ALAN = $("input[name='BELEDIYE_MUCAVIR_ALAN']:checked").val();
debugger
data.OSB_YERLESIK = $("input[name='OSB_YERLESIK']:checked").val();
data.KIYI_TESISI = $("input[name='KIYI_TESISI']:checked").val();
data.VERSIYON = $("input[name='VERSIYON']:checked").val();
data.SANAYI_TIPI = window.localStorage.getItem("sanayitipiid");
window.localStorage.removeItem("sanayitipiid");
debugger
var jsondata = JSON.stringify(data);
$.ajax({
type: "POST",
contentType: 'application/json',
url: "/KurulusBilgileri/KurulusBilgileriniGuncelle",
data: jsondata,
success: function (result) {
debugger
var jsondata = JSON.parse(result)
if (jsondata.Passed) {
debugger
$('#tdISIM').empty();
$('#tdISIM').append(data.ISIM);
$('#tdADRES_METIN').empty();
$('#tdADRES_METIN').append(jsondata.data.ADRES_METIN);
$('#tdTELEFON').empty();
$('#tdTELEFON').append(jsondata.data.TELEFON);
$('#tdFAKS').empty();
$('#tdFAKS').append(jsondata.data.FAKS);
$('#tdE_POSTA').empty();
$('#tdE_POSTA').append(jsondata.data.E_POSTA);
$('#tdSORUMLU_ISIM').empty();
$('#tdSORUMLU_ISIM').append(jsondata.data.SORUMLU_ISIM);
$('#tdSANAYI_TIPI > #tdtxtSANAYI_TIPI').empty();
$('#tdSANAYI_TIPI > #tdtxtSANAYI_TIPI').append(jsondata.data.SANAYI_TIPI);//sanayitipi id si...
$('#tdFAALIYET_ALANI > #tdtxtFAALIYET_ALANI').empty();
$('#tdFAALIYET_ALANI > #tdtxtFAALIYET_ALANI').append(jsondata.data.FAALIYET_ALANI);
$('#tdCEVRE_BILGI > #tdtxtCEVRE_BILGI').empty();
$('#tdCEVRE_BILGI > #tdtxtCEVRE_BILGI').append(jsondata.data.CEVRE_BILGI);
debugger
if (jsondata.data.BELEDIYE_MUCAVIR_ALAN == "1") {
$("#tdBELEDIYE_MUCAVIR_ALAN > input[name='radioBelediyeMucavirAlan']").prop('checked', true);
}
else
$("#tdBELEDIYE_MUCAVIR_ALAN > input[name='radioBelediyeMucavirAlan']").prop('checked',false);
if (jsondata.data.OSB_YERLESIK == "1") {
$("#tdOSB_YERLESIK > input[name='radioOsbYerlesik']").prop('checked', true);
}
else
$("#tdOSB_YERLESIK > input[name='radioOsbYerlesik']").prop('checked',false);
if (jsondata.data.KIYI_TESISI == "1") {
$("#tdKIYI_TESISI > input[name='radioKiyiTesisi']").prop('checked', true);
}
else
$("#tdKIYI_TESISI > input[name='radioKiyiTesisi']").prop('checked',false);
if (jsondata.data.VERSIYON == "1") {
$("#tdVERSIYON > input[name='radioVersion']").prop('checked', true);
}
else
$("#tdVERSIYON > input[name='radioVersion']").prop('checked',false);
}
},
error: function () {
alert("ajax process in error");
}
});
}
</script>
kurulusbilgileri.js:
$(function () {
$("#btnSanayiTipiKaydet").on('click', sanayitipleriKaydet)
});
sanayiTipiTextGetir = function (id)
{
var text = $('input[id=' + id + ']').val();
debugger;
return text;
}
sanayitipilistesinigoster = function () {
$("#stack2").show();
}
sanayitipiTotextarea = function (id) {
$("#divSanayiTipi").show(600, null);
var sanayitipi = $("#" + id).val();
window.localStorage.setItem("sanayitipiid", id);
$("#input_sanayitipi").val(sanayitipi);
$("#input_id").val(id);
$("#stack2").modal('toggle');
}

Since you load your partial trough a modal, I'm assuming that the actual loading is done using AJAX. This means that when you first load your HTML page (the initial one), the partial is not yet part of the DOM (might have not been requested from the server). This in turn means that you checkbox is also not part of the DOM, and therefore is returned as undefined.

Related

How can i render partial view as modal popup on button click?

I am trying to render partial view from controller on button click event to view the details. But unfortunately its not working.
My Controller Action
OwnerController.cs
public IActionResult ShowpopUp(int id) {
var venue = _context.Venues.FirstOrDefault(x=>x.Id==id);
return PartialView(venue);
}
My View All.cshtml
#model List<Venue>
<table class="table table-hover">
<thead>
<th> Property Name </th>
<th colspan="2">Action</th>
</thead>
<tbody>
#foreach(var x in Model)
{
<tr>
<td>
#x.Name
</td>
<td>
<a class="btn btn-default btn-sm" id="#x.Id" onclick="Details(this.id)">Show</a>
</td>
</tr>
}
</tbody>
</table>
<script>
function Details(id)
{
$.get("#Url.Action("ShowpopUp","Owner")/"+id,
function(data) {$('.modal-body').html(data);})
$("#myModal").modal("show");
}
$('#myModal').on('hidden.bs.modal', function(e){
$('.modal-body').html("");
})
}
</script>
myModal
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Details</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The following example should help achieve your requirement of rendering partial view as modal popup using jQuery Ajax, please check it.
All.cshtml
#model IEnumerable<Venue>
#{
ViewData["Title"] = "All";
}
<h1>All</h1>
<table class="table table-hover">
<thead>
<th> Property Name </th>
<th colspan="2">Action</th>
</thead>
<tbody>
#foreach (var x in Model)
{
<tr>
<td>
#x.Name
</td>
<td>
<a class="btn btn-default btn-sm" id="#x.Id" onclick="Details(this.id)">Show</a>
</td>
</tr>
}
</tbody>
</table>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Details</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#section scripts{
<script>
function Details(id) {
$.get("#Url.Action("ShowpopUp","Owner")/" + id,
function (data) {
$('.modal-body').html(data);
});
$("#myModal").modal("show");
}
</script>
}
ShowpopUp action
public IActionResult ShowpopUp(int id)
{
var venue = _context.Venues.FirstOrDefault(x => x.Id == id);
//specify the name or path of the partial view
return PartialView("_VenueDetail", venue);
}
_VenueDetail.cshtml (partial view under Views/Shared folder)
#model Venue
<h1>Venue Details</h1>
<h2>Id: #Model.Id</h2>
<h2>Name: #Model.Name</h2>
Test Result

Displaying a Modal in Partial View in Asp.net Mvc

After clicking "Advanced search" button i want to open a modal from a partial view where i can apply custom search
Here is my Index.cshtml page for showing data table
#model SmartAdmission.Web.Areas.Admin.Models.InstituteViewModel
#{
ViewBag.Title = "Index";
Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";
}
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box">
<div class="box-header">
<h3 class="box-title">Program Level List</h3>
</div>
<div class="box-body">
#if (TempData["Message"] != null)
{
<div class="alert alert-#TempData["alertType"]">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
#TempData["Message"]
</div>
}
#*<input type="hidden" id="hiddenProvinceId" />*#
<table id="instituteTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>
<button type="button"
class="btn btn-default btn-md" data-toggle="modal"
data-target="#advancedSearchModal"
id="advancedsearch-button">
<span class="glyphicon glyphicon-search"
aria-hidden="true"></span> Advanced Search
</button>
</th>
</tr>
<tr>
<th>Institute Name</th>
<th>Province</th>
<th>Course Name</th>
<th>Program Level</th>
<th>Tution Fee</th>
<th>Ielts</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#{
foreach (var institute in Model.Institutes)
{
<tr>
<td>
#Html.DisplayFor(m => institute.InstituteName)
</td>
<td>
#Html.DisplayFor(m => institute.Province.Name)
</td>
#foreach (var discipline in institute.Disciplines)
{
foreach (var course in discipline.Courses)
{
<td>
#Html.DisplayFor(m => course.CourseName)
</td>
<td>
#Html.DisplayFor(m => course.ProgramLevel.Name)
</td>
<td>
#Html.DisplayFor(m => course.TutionFeePerYear)
</td>
<td>
#Html.DisplayFor(m => course.IeltsMinRequirement)
</td>
}
}
<td>
<a href="#Url.Action("EditInstitute", "Institute" , new { id = institute.Id }, null)" class="btn">
<i class="glyphicon glyphicon-edit"></i>
</a>
<i class="glyphicon glyphicon-trash"></i>
</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
</div>
</div>
</section>
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="/Admin/Institute/DeleteInstitute" method="post">
<div class="modal-header">
<h5 class="modal-title">Delete Item</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Do you want to delete this record?</p>
<input type="hidden" id="id" name="id" value="" />
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger">Yes, Delete!</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
#section scripts
{
<script>
$(document).ready(function () {
$('#instituteTable').DataTable()
});
$(function () {
$("#mydialog").dialog({
modal: true,
width: "800px",
autoOpen: false
});
});
function ConfirmDelete(id) {
$("#id").val(id);
$('.modal').modal('show');
}
</script>
}
This is my partial view
#model SmartAdmission.Web.Areas.Admin.Models.AdvanceSearchModel
<div id="advancedSearchModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="/Admin/Institute/GetCustomInstitute" method="post">
<div class="modal-header">
<h5 class="modal-title">Advance Search</h5>
#*<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>*#
</div>
<div class="modal-body">
#Html.TextBoxFor(m=>m.InstituteName)
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger">Yes, Delete!</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
i have tried ajax call on button click and refer the url to the action which return a partial view but that didn't work for me.

Boostrap Modal not working on ASP.NET MVC

I have readed a lot of blogs and articles about showing MVC partial views using Boostrap modals. It seems that I have exactly what I'm seen on the material consulted but still it doesn't show the modal. I just need to show the partial view with the Album details in a modal. The controller is working fine when I load the URL through the browser.
This is the Index HTML code where the modal is shown:
<tbody>
#foreach( var album in Model.Albums)
{
<tr data-toggle="modal" data-target="#albumModal" data-url="#Url.Action("Album", new { id = album.Id })">
<td>#album.Title</td>
<td>#album.Artist</td>
<td>#album.Genre</td>
<td>#album.Year</td>
</tr>
}
</tbody>
Partial View
<div class="modal fade" id="albumModal" tabindex="-1" role="dialog" aria-labelledby="albumModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="albumModalLabel">Album Details</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-4">
<div class="row">
<label>Album<input class="form-control" type="text" id="title" /></label>
</div>
<div class="row">
<label>Artist <input class="form-control" type="text" id="artist" /></label>
</div>
<div class="row">
<label>Genre <input class="form-control" type="text" id="genre" /></label>
</div>
<div class="row">
<label>Year <input class="form-control" type="text" id="year" /></label>
</div>
</div>
<div class="col-md-8">
<table class="table table-condensed table-striped">
<thead>
<tr>
<th>Track</th>
<th>Song Title</th>
<th>Length</th>
</tr>
</thead>
<tbody class="tracks"></tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
HomeController
[HttpGet]
public ActionResult Album(int? id)
{
if (id == null) return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
var albumInfo = _service.GetAlbumInfo((int) id);
if (albumInfo == null) return HttpNotFound();
return PartialView("_Album", albumInfo);
}
Script
$(document).ready(function() {
$('.list-element').click(function () {
debugger;
var $buttonClicked = $(this);
var url = $buttonClicked.attr('data-url');
$.get(url, function (data) {
$('#albumContainer').html(data);
$('#albumModal').modal('show');
});
});
});
In almost all of the SO questions counsulted, they wasn't using data-target but I am. What do I need to modify to achieve that the modal shows?
VIEW
#model ShowModal
<table>
<tbody>
<tr data-toggle="modal" data-target="#albumModal" data-url="#Url.Action("Album", new { id = album.Id })">
<td>#album.Title</td>
<td>#album.Artist</td>
<td>#album.Genre</td>
<td>#album.Year</td>
</tr>
</tbody>
</table>
<!-- Modal -->
<div class="modal" id="albumModal" tabindex="-1" role="dialog" aria-labelledby="albumModal">
#Html.Partial("_albumPartial", Model)
</div>
CONTROLLER
[HttpGet]
public ActionResult Album(int? id)
{
ShowModal modal = new ShowModal();
var albumInfo = _service.GetAlbumInfo((int) id);
modal.Info1 = albumInfo.Info1;//and other fields
return PartialView("_albumPartial", modal);
}
SCRIPT
<script>
$(document).ready(function () {
$("#albumModal").on("show.bs.modal", function (e) {
var button = $(event.relatedTarget) // Button that triggered the modal
var url = button.data('url') // or button.attr("data-url") or get here just the id and create the URL here
$.get(url, function (data) {
$('#albumModal').html(data);
$('#albumModal').modal('show');
});
});
});
</script>

Delete Confirm with Bootstrap modal in Asp.Net MVC

I am trying to make a dialog with bootstrap modal to confirm a delete. The delete works well, except it doesn't get the data which I select but it gets the first data in ID order from the database. I am new on client-side programming, so if someone could help me it would be nice.
The code is:
[HttpPost]
public async Task<ActionResult> Delete(int id)
{
RepFilter repFilter = await db.RepFilters.FindAsync(id);
db.RepFilters.Remove(repFilter);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
(razor)
#foreach (var item in Model)
{
using (Html.BeginForm("Delete", "RepFilters", new { id = item.ID }))
{
<tr>
<td>#index</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Report.Description)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID }) |
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#myModal">Delete</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>
</div>
<div class="modal-body">Are you sure you want to delete: <span><b>#item.Description</b></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" value="Delete" class="btn btn-danger" />
</div>
</div>
</div>
</div>
</td>
</tr>
}
}
</tbody>
The button that opens the modal is getting the right ID, but the modal doesn't!
So how to make the modal take the adequate data to delete?
I am trying to avoid writing javascript and use data attributes, until there is no other choice
The modal this way has the same ID, no matter which data you try to delete.
So just add a variable to specify different ID for the mmodal:
using (Html.BeginForm("Delete", "RepFilters", new { id = item.ID }))
{
var myModal = "myModal" + item.ID;
<tr>
<td>...</td>
<td>...</td>
<button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="##myModal">Delete</button>
<!-- Modal -->
<div class="modal fade" id="#myModal" tabindex="-1" role="dialog" data-keyboard="false" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-sm">
...........<!--And the rest of the modal code-->
There are actually quite a few things you may want to address in your view. You are looping through the items in your model, and creating a separate form (and modal)for each item. This is probably not ideal, however if you really want to do it this way you can add a reference to the item id within the html for the modal. Just add a hidden input and set it's value to item.id.
However, I would not recommend this approach. I'm not certain for your reasons on wanting to shy away from JavaScript, but the functionality you want to create here is actually pretty basic.
See this post: Confirm delete modal/dialog with Twitter bootstrap?
Edit:
#foreach (var item in Model)
{
<tr>
<td>#index</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Report.Description)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
#Html.ActionLink("Details", "Details", new { id = item.ID }) |
<button type="button" class="btn btn-danger btn-sm" data-item-id="#item.ID" data-item-description="#item.Report.Description" data-toggle="modal" data-target="#confirm-delete">Delete</button>
</td>
</tr>
}
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>
</div>
<div class="modal-body">
Are you sure you want to delete: <span class="description"></span>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" value="Delete" class="btn btn-danger" />
</div>
</div>
</div>
<script>
$('#confirm-delete').on('click', '.btn-ok', function(e) {
var $modalDiv = $(e.delegateTarget);
var id = $(this).data('itemId');
$modalDiv.addClass('loading');
$.post('/RepFilters/Delete/' + id).then(function () {
$modalDiv.modal('hide').removeClass('loading');
});
});
$('#confirm-delete').on('show.bs.modal', function(e) {
var data = $(e.relatedTarget).data();
$('.description', this).text(data.itemDescription);
$('.btn-ok', this).data('itemId', data.itemId);
});
</script>
You first write a delete function in jquery .for displaye confirm message you can use sweetalert and write a custom file for sweetalert.
yo must add refrence sweetalert css and script in your view page.
function Delete(id) {
var submitdelete=function(){ $.ajax({
url: '#Url.Action("/mycontroller/Delete)',
type: 'Post',
data: { id: id }
})
.done(function() {
$('#' + id).remove();//if you want to delete table row
msgBox.success("Success","Ok");
});}
msgBox.okToContinue("warning", "Are you sure to delete ?", "warning", "ok","cancel", submitdelete);
}
Confirm dialog
var msgBox = {
message: {
settings: {
Title: "",
OkButtonText: "",
type:"info"
}
},
okToContinue: function(title, text, type, okButtonText,closeButtonText, isConfirmDo) {
swal({
title: title,
text: text,
type: type,
showCancelButton: true,
confirmButtonClass: 'btn-danger',
confirmButtonText: okButtonText,
cancelButtonText: closeButtonText,
closeOnConfirm: false,
closeOnCancel: true
},
function(isConfirm) {
if (isConfirm) {
isConfirmDo();
}
});
},
confirmToContinue: function(title, text, type, confirmButtonText, cancelButtonText, isConfirmDo, isNotConfirmDo, showLoader) {
if (!showLoader) {
showLoader = false;
}
swal({
title: title,
text: text,
type: type,
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: confirmButtonText,
cancelButtonText: cancelButtonText,
closeOnConfirm: true,
closeOnCancel: true,
showLoaderOnConfirm: showLoader
},
function(isConfirm) {
if (isConfirm) {
isConfirmDo();
}
});
} ,
success: function (title, text,okButtontex) {
swal({
title: title,
text: text,
type: "success",
confirmButtonText: okButtontex
});
},
info: function (title, text) {
swal({
title: title,
text: text,
type: "info",
confirmButtonText: "OK"
});
},
warning: function (title, text) {
swal({
title: title,
text: text,
type: "warning",
confirmButtonText: "OK"
});
},
error: function (title, text) {
swal({
title: title,
text: text,
type: "error",
confirmButtonText: "OK"
});
},
}
Here's an easy way to do this. You should be able to adapt what i did here to your case. This requires very little javascript code.
<script>
var path_to_delete;
var root = location.protocol + "//" + location.host;
$("#deleteItem").click(function (e) {
path_to_delete = $(this).data('path');
$('#myform').attr('action', root + path_to_delete);
});
</script>
<table class="table table-hover" id="list">
<thead class="bg-dark text-white">
<tr>
<th>
Edit
</th>
<th>
Employee
</th>
<th>
Effective Date
</th>
<th>
ST/OT/DT
</th>
<th>
Other Pay
</th>
<th>
Job
</th>
<th>
Pending?
</th>
<th>
Delete
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
<a class="btn btn-sm" href="~/Employees/TerminationEdit/#item.Employee_Termination_Info_Id">
<i class="fa fa-lg fa-pencil-alt text-dark"></i>
</a>
</td>
<td>
#Html.DisplayFor(modelItem => item.Employee_Name_Number)
</td>
<td>
#Html.DisplayFor(modelItem => item.Effective_Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.Employee_Time)
</td>
<td>
#Html.DisplayFor(modelItem => item.Employee_Other_Pay)
</td>
<td>
#Html.DisplayFor(modelItem => item.Job_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Pending)
</td>
<td>
<a id="deleteItem" class="btn btn-sm" data-toggle="modal" data-target="#deleteModal"
data-path="/Employees/TerminationDelete/#item.Employee_Termination_Info_Id">
<i class="fa fa-lg fa-trash-alt text-danger"></i>
</a>
</td>
</tr>
}
</tbody>
</table>
<!-- Logout Modal-->
<div class="modal fade" id="deleteModal" 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">Are you sure?</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">Are you sure you want to delete this termination record? <br /><span class="text-danger">This cannot be undone.</span></div>
<div class="modal-footer">
<button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
#using (Html.BeginForm("TerminationDelete", "Employees", FormMethod.Post, new { id = "myform", #class = "" }))
{
#Html.AntiForgeryToken()
<input type="submit" value="Delete" id="submitButton" class="btn btn-danger" />
}
</div>
</div>
</div>
</div>
So what happens here, is that the page will cycle through the model and draw the delete button (using font awesome). Note that here is is setting the data-path attribute for later use. When the button is clicked, it sets the form action for the button on the modal popup immediately. This is important, since it has a form around the delete button, it will send it to a POST and not a GET, as Rasika and Vasil Valchev pointed out. Plus, it has the benefit of the anti-forgery token.

Cant display values to Textbox's at second time using Jquery

I am developing MVC application.
I have shown the confirm modal box.
It works properly only at once.... If I open it again it didnt work at all...
check below picture....
when I put the entries in the dispatch text box(34), on blur event it multiplies bundle size value(60) and shows in Pisces text box (2040). its working fine,
when I close the box and open it again and put the values again in dispatch text box, its not working at all...
Here is my code...
<h2 style="font-size:22px;">Dispatch </h2>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm("Create", "Dispatch", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmCreate" }))
{
#Html.ValidationSummary(true)
<div class="row-fluid">
<div class="span12 roundedDiv" >
<div class="span12" style="margin-left:0px; margin-bottom:10px;">
<legend style="color:#ee8929; font-size:16px;">Primary Information</legend>
</div>
<div class="span12" style="margin-left:0px; margin-bottom:10px;">
<legend style="color:#ee8929; font-size:16px;">Product List</legend>
<div class="row-fluid">
<table class="table table-striped table-hover" id="mytable">
<thead>
<tr >
<th>
Section Name
</th>
<th>
Section Code
</th>
</tr>
</thead>
<tbody id="tbody">
#foreach (var item in ViewBag.ProductList)
{
<tr id="tableRow" >
<td >
#item.SectionName
</td>
<td >
#item.SectionCode
</td>
<td id="editRow" >
Edit
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
<div class="span11" >
<div class="span3"> Order Date : #System.DateTime.Now.ToShortDateString()</div>
<div class="span9" style="text-align:right">
<button type="button" class="btn btn-primary" id="btnDispatch" >Dispatch</button>
<input class="btn btn-default" value="Back" style="width:40px;" onclick="window.location.href='#Url.Action("index") '"/>
</div>
</div>
</div>
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$('.editClass').click(function () {
$('body').append('<div id="dataConfirmModal" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true" id="btnClose1"> × </button><h5 id="dataConfirmLabel">Edit </h5> </div><div class="modal-body" ><html><table style="width:530px"><tr> <th style="width:120px">Bundle Size</th><th>Count</th><th>Dispatch</th> <th> Pieces</th> </tr><tr> <td><div id="bundleSize1" >60 </div></td> <td><div id="count1">3</div></td> <td><input id="dispatchValue1" type="text" style="width:100px ;height:15px ;margin:1px" /></td> <td> <input id="pieces1" type="text" style="width:100px ;height:15px ;margin:1px" disabled/></td> </tr> <tr> <td><div id="bundleSize2" >10</div></td> <td><div id="count2">8</div></td><td><input id="dispatchValue2" type="text" style="width:100px ;height:15px ;margin:1px" /></td><td> <input id="pieces2" type="text" style="width:100px ;height:15px ;margin:1px" disabled/></td> </tr> <tr style="border-bottom:solid #e8eef4 thick;"> <td><div id="bundleSize3" >1</div></td><td><div id="count3">20</div></td><td><input id="dispatchValue3" type="text" style="width:100px ;height:15px ;margin:1px" /></td><td> <input id="pieces3" class="txt" type="text" style="width:100px ;height:15px ;margin:1px" disabled/></td> </tr> <tr> <td colspan="3" style ="text-align: right; border-right:solid white;"> Total</td> <td> <input id="total" type="text" value="0" style="width:100px ;height:15px ;margin:1px" disabled /></td></tr></table> </html></div> <div class="modal-footer"><button type="button" id="btnOk1" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" >OK</button> <button type="button" id="btnCancel1" class="btn btn-default" data-dismiss="modal" aria-hidden="true" >Cancel</button> </div></div> ');
$('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
$('#dataConfirmModal').modal({ show: true });
});
$('body').on('click', '#btnOk1', function() {
});
$('body').on('click', '#btnCancel1', function() {
var url="#Url.Action("DispatchNow")";
$(location).attr('href', url);
});
$('body').on('click', '#btnClose1', function() {
var url="#Url.Action("DispatchNow")";
$(location).attr('href', url);
});
Below is the Blur event of textbox, where calculation take place. calculation is ok...but value dont assigned to Pieces textbox.
$('body').on('blur', '#dispatchValue1', function() {
var dispatchValue = $('#dispatchValue1').val();
var bundleSize = $('#bundleSize1').text();
var nPieces1 = dispatchValue*bundleSize;
$('#pieces1').val(nPieces1);
var ntotal= $('#total').text();
$('#supplyQuantity').val(sum);
if(ntotal > 0)
{
var ntotal = $('#total').val();
var sum = parseFloat(ntotal) +parseFloat(nPieces1);
$('#pieces1').val(sum);
$('#total').val(sum);
$('#supplyQuantity').val(sum);
}
else
{
var sum = parseFloat(nPieces1);
$('#pieces1').val(sum);
$('#total').val(sum);
$('#supplyQuantity').val(sum);
}
});
});
$(document).ready(function () {
$('#btnDispatch').click(function () {
$('body').append('<div id="dataConfirmModal1" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true" id="btnClose"> × </button> <h5 id="dataConfirmLabel">Dispatch Alert</h5> </div><div class="modal-body"><h5>This order is dispatched.</h5><br/></div><div class="modal-footer"><button type="button" id="btnOk" class="btn btn-primary" data-dismiss="modal" aria-hidden="true" >OK</button> </div></div> <div class="modal-backdrop"></div>');
$('#dataConfirmModal1').find('.modal-body').text($(this).attr('data-confirm'));
$('#dataConfirmModal1').modal({ show: true });
});
$('body').on('click', '#btnOk', function() {
var url="#Url.Action("index")";
$(location).attr('href', url);
});
$('body').on('click', '#btnClose', function() {
var url="#Url.Action("index")";
$(location).attr('href', url);
});
});
</script>
Can you please call alert in this code block;
$('body').on('blur', '#dispatchValue1', function() {
var dispatchValue = $('#dispatchValue1').val();
alert(dispatchValue );
var bundleSize = $('#bundleSize1').text();
alert(bundleSize);
var nPieces1 = dispatchValue*bundleSize;
$('#pieces1').val(nPieces1);
I think at second time one of that alert values is null or empty. Check that please. You lose the control of that field.

Resources