JQuery not working in PartialView inside modal dialog - javascript

I'm trying to create a "Create" form as a modal dialog when the user clicks the create button. The Modal displays the partialview that contains the form. But when the user selects a value in the dropdownlist it should us AJAX to populate other information on the form. But the jquery call to lookupVendor information doesn't fire. I know i'm missing something, but just can't see it.. So any help would be great.
Controller
public ActionResult LookupVendor(int? id)
{
string VendorContact = "";
string VendorPartNumber = "";
decimal VendorPrice = 0;
if (id != null)
{
var vendors = (from v in dbVendor.vendors where v.idVendor == id select v).ToList();
var tmpnumber = (from x in dbVendor.vendorpartinformations where x.IDVendor == id && x.IDParts == id select x).ToList();
foreach (var item in vendors)
{
VendorContact = item.Contact;
}
if (tmpnumber.Count != 0)
{
foreach (var item1 in tmpnumber)
{
VendorPartNumber = item1.VendorPartNumber;
VendorPrice = (decimal)item1.VentorPrice;
}
}
else
{
VendorPartNumber = "Not available from this Vendor";
}
}
return Json(new { VendorContact = VendorContact, VendorPartNumber = VendorPartNumber, VendorPrice = VendorPrice }, JsonRequestBehavior.AllowGet);
}
public ActionResult Create(int? id, int? idVendor, int? idReference, int? Required, RequisitionOrder model)
{
foreach (var Vendor in dbVendor.vendors)
{
model.VendorNames.Add(new SelectListItem { Text = Vendor.Name, Value = Vendor.idVendor.ToString() });
}
var Tmpdetails = dbParts.parts.Where(x => x.idParts == id).ToList();
foreach(var item2 in Tmpdetails)
{
model.PartNumber = item2.PartNumber;
model.PartDescription = item2.PartDescription;
model.StockQTY = (int)item2.PartQTY;
if(Required != null)
{
model.RequisitionQTY = (int)Required;
}
else
{
model.RequisitionQTY = (int)model.RequisitionQTY;
}
foreach(var item3 in dbPartType.parttypes)
{
if(item3.idPartType == item2.PartType)
{
model.PartType = item3.PartType1;
}
}
}
return PartialView("Create", model);
}
Main Form
#model MYSQL___Parts_Management.Models.ItemsToOrder
#{
ViewBag.Title = "ItemsToOrder";
}
<style>
table, th, td {
border: 0px solid black;
padding: 5px;
/*font-size: 12px;*/
}
table.center {
margin-left: auto;
margin-right: auto;
}
table {
border-spacing: 15px;
}
.foo {
color: red;
}
.modal-dialog {
position: relative;
display: table; /* <-- This makes the trick */
overflow-y: auto;
overflow-x: auto;
width: auto;
min-width: 300px;
}
</style>
<br />
<br />
#using (Html.BeginForm("ItemToOrder", "PartRequisitions", FormMethod.Post))
{
#Html.AntiForgeryToken()
<table style="filter: alpha(opacity=40); opacity: 0.95;border:2px black solid;width:100%" ;table-layout:fixed;>
<tr>
<th colspan="9" bgcolor="#dddddd" cellspacing="1" cellpadding="6" style="font-size: 15px;border:1px black solid;padding-left:0.8ex">Parts Order</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<th style="font-weight:bold;font-size: 14px;text-align:center;padding-left:2.0ex" nowrap>Part Description</th>
<th style="font-weight:bold;font-size: 14px;text-align:center;padding-left:2.0ex" nowrap>Part Number</th>
<th style="font-weight:bold;font-size: 14px;text-align:center;padding-left:2.0ex" nowrap>Minimum QTY</th>
<th style="font-weight:bold;font-size: 14px;text-align:center;padding-left:2.0ex" nowrap>Maximum QTY</th>
<th style="font-weight:bold;font-size: 14px;text-align:center;padding-left:2.0ex" nowrap>Stocked QTY</th>
<th style="font-weight:bold;font-size: 14px;text-align:center;padding-left:2.0ex" nowrap>Requested QTY</th>
<th style="font-weight:bold;font-size: 14px;text-align:center;padding-left:2.0ex" nowrap>Required QTY</th>
<th></th>
<th></th>
</tr>
#if (Model.Results.Count > 0)
{
foreach (var item in Model.Results)
{
<tr style="font-size:12px; font-weight: bold">
#if (item.QTYDifference != 0)
{
<td width="230" nowrap>
#Html.DisplayFor(modelItem => item.PartDescription) #Html.DisplayFor(modelItem => item.idParts)
</td>
<td nowrap align="center">
#Html.DisplayFor(modelItem => item.PartNumber)
</td>
<td nowrap align="center">
#Html.DisplayFor(modelItem => item.PartMinQTY)
</td>
<td align="center">
#Html.DisplayFor(modelItem => item.PartMaxQTY)
</td>
<td align="center">
#Html.DisplayFor(modelItem => item.PartQTY)
</td>
<td align="center">
#Html.DisplayFor(modelItem => item.RequestedQTY)
</td>
<td align="center">
#Html.DisplayFor(modelItem => item.QTYDifference)
</td>
<td> #Html.ActionLink(" ", "Create", "PartRequisitions", new { #id = item.idParts, #Required = item.QTYDifference }, new { #class = "glyphicon glyphicon-list-alt", #title = "Create PO", #data_modal = "" })</td>
<td></td>
}
</tr>
}
}
<tr>
<td colspan="9"></td>
</tr>
</table>
}
<div id='myModal' class='modal fade'>
<div class="modal-dialog">
<div class="modal-content">
<div id='myModalContent'></div>
</div>
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/scripts/appjs/PRequisitionIndex.js")
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
}
Main Form - Script file
$(document).ready(function () {
$(window).keydown(function (event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$('#progress').show();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
$('#progress').hide();
window.location.href = "/PartRequisitions/ItemsToOrder";
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}
$(document).ready(function () {
$('#data').after('<div id="nav"></div>');
var rowsShown = 10;
var rowsTotal = $('#data tbody tr').length;
var numPages = rowsTotal / rowsShown;
for (i = 0; i < numPages; i++) {
var pageNum = i + 1;
$('#nav').append('' + pageNum + ' ');
}
$('#data tbody tr').hide();
$('#data tbody tr').slice(0, rowsShown).show();
$('#nav a:first').addClass('active');
$('#nav a').bind('click', function () {
$('#nav a').removeClass('active');
$(this).addClass('active');
var currPage = $(this).attr('rel');
var startItem = currPage * rowsShown;
var endItem = startItem + rowsShown;
$('#data tbody tr').css('opacity', '0.0').hide().slice(startItem, endItem).
css('display', 'table-row').animate({ opacity: 1 }, 300);
});
});
Create Form as partial view
#model MYSQL___Parts_Management.Models.RequisitionOrder
#{
ViewBag.Title = "Parts Requisition";
Layout = "";
}
<style>
table, th, td {
border: 0px solid black;
padding: 5px;
/*font-size: 12px;*/
}
table.center {
margin-left: auto;
margin-right: auto;
}
table {
border-spacing: 15px;
}
</style>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
#using (Html.BeginForm("Create", "partrequisitions", FormMethod.Post, new { id = "form" } ))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
#Html.HiddenFor(c => c.idReference)
#Html.HiddenFor(c => c.ReferenceNumber)
#Html.HiddenFor(c => c.PartDescription)
#Html.HiddenFor(c => c.PartNumber)
#Html.HiddenFor(c => c.StockQTY)
#Html.HiddenFor(c => c.PartType)
#Html.HiddenFor(c => c.RequisitionQTY)
<div class="modal-body">
<table style="filter: alpha(opacity=40); opacity: 0.95;border:2px black solid;width:100%" ;table-layout:fixed;>
<tr>
<th colspan="4" bgcolor="#dddddd" cellspacing="1" cellpadding="6" style="font-size: 15px;border:1px black solid;padding-left:0.8ex">Part Information</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Part Category:</td>
<td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex" nowrap>#Html.DisplayFor(c => c.PartType)</td>
<td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Part Number:</td>
<td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex" nowrap>#Html.DisplayFor(c => c.PartNumber)</td>
</tr>
<tr>
<td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Description:</td>
<td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex" nowrap>#Html.DisplayFor(C => C.PartDescription)</td>
<td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Stocked QTY:</td>
<td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex">#Html.DisplayFor(C => C.StockQTY)</td>
</tr>
</table>
<br />
<table style="filter: alpha(opacity=40); opacity: 0.95;border:2px black solid;width:100%" ;table-layout:fixed;>
<tr>
<th colspan="5" bgcolor="#dddddd" cellspacing="1" cellpadding="6" style="font-size: 15px;border:1px black solid;padding-left:0.8ex">Order Information</th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Vendor:</td>
<td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex" nowrap>
#Html.DropDownListFor(m => m.idVendor, Model.VendorNames, "-- Select Vendor --", new { #id = "VendorName1", style = "width: 200px;", required = "required" })
#Html.ValidationMessageFor(m => m.idVendor, "", new { #class = "text-danger" })
</td>
<td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Reference Number:</td>
<td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex" nowrap>#*#Html.DropDownListFor(m => m.idReference, Model.ReferenceNumbers, "-- Select Reference Number --", new { style = "width:900px", id = "ReferenceNumber1" })*#</td>
<td></td>
</tr>
<tr>
<td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Contact:</td>
<td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex" nowrap> #Html.DisplayFor(m => m.VendorContact) </td>
<td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Vendor Number:</td>
<td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex" nowrap>#Html.DisplayFor(m => m.VendorPartNumber)</td>
<td></td>
</tr>
<tr>
<td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Vendor Price: ($)</td>
<td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex">#Html.TextBoxFor(C => C.VendorPrice, new { htmlAttributes = new { #oncut = "return false", #oncopy = "return false", #onpaste = "return false", #type = "number", #min = "0", #max = "999", #id = "VendorPrice" }, style = "width:50px;" })</td>
<td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Confirmed Price:</td>
<td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex">
#Html.RadioButtonFor(c => c.ConfirmedPrice, 0) No #Html.RadioButtonFor(c => c.ConfirmedPrice, 1) Yes
</td>
<td></td>
</tr>
<tr>
<td style="font-weight:bold;font-size: 14px;padding-left:3.0ex;padding-top:0.8ex">Order Qty:</td>
<td style="font-weight:normal;font-size: 14px;padding-left:0.8ex;padding-top:0.8ex">#Html.TextBoxFor(c => c.RequisitionQTY, new { htmlAttributes = new { #oncut = "return false", #oncopy = "return false", #onpaste = "return false", #type = "number", #min = "0", #max = "999", #id = "RequisitionQTY" }, style = "width:50px;" })</td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<br />
</div>
<div class="modal-footer">
<table class="center">
<tr>
<td style="text-align:center">
<input type="submit" value="Save" class="btn btn-primary" />
</td>
<td style="text-align:center"><button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button></td>
</tr>
</table>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/Scripts/Appjs/PRequisitionCreate.js")
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script type="text/javascript">
$("form").removeData("validator");
$("form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("form");
</script>
}
Create Form - Script File
$(document).ready(function () {
$(window).keydown(function (event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
$("#RequisitionQTY").keydown(function (evt) {
evt = (evt) ? evt : window.event;
let charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode > 31 && ((charCode < 48 || charCode > 57) && (!(charCode >= 96 && charCode <= 105)))) && charCode != 46) {
evt.preventDefault();
}
else {
return true;
}
});
$("#VendorPrice").keydown(function (evt) {
evt = (evt) ? evt : window.event;
let charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode > 31 && ((charCode < 48 || charCode > 57) && (!(charCode >= 96 && charCode <= 105)))) && charCode != 46 && charCode != 110) {
evt.preventDefault();
}
else {
return true;
}
});
$("#VendorName1").change(function () {
var tempID = document.getElementById("VendorName1");
$.ajax({
type: 'POST',
url: '#Url.Action("LookupVendor", "partrequisitions")',
dataType: 'json',
data: { id: tempID },
success: function (data) {
$("#myModalContent").html(data);
}
});
});
ViewModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace MYSQL___Parts_Management.Models
{
public class RequisitionOrder
{
//DropDownListFor data
public RequisitionOrder()
{
this.VendorNames = new List<SelectListItem>();
}
public List<SelectListItem> VendorNames { get; set; }
public int idVendor { get; set; }
public int idReference { get; set; }
//DisplayFor data
public int ReferenceNumber { get; set; }
public string PartType { get; set; }
public string PartNumber { get; set; }
public string PartDescription { get; set; }
public int StockQTY { get; set; }
public string VendorName { get; set; }
public string VendorContact { get; set; }
public string VendorPhone { get; set; }
public string VendorPartNumber { get; set; }
[DisplayFormat(DataFormatString = "{0:C}")]
[Required(ErrorMessage = "Vendor Price required")]
public decimal VendorPrice { get; set; }
public int ConfirmedPrice { get; set; }
public int RequisitionQTY { get; set; }
public int ReceivedQTY { get; set; }
public int PReceivedQTY { get; set; } /*Previously Received QTY*/
}
}
Layout (Nav Bar)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>#ViewBag.Title - My ASP.NET Application</title>
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">
<img src="~/upload/logo.png" style="height:auto; width:30%; margin-top:-15px"/>
</a>
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
#Html.ActionLink("Part Management System", "Index", "Home", new { area = "" }, new { #class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
#if (Request.IsAuthenticated)
{
<li class="dropdown">
Help<span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>#Html.ActionLink("About", "About", "Home")</li>
<li>#Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</li>
}
#* Rest of Nav Menu truncated because of space. *#
</ul>
#Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
#RenderBody()
<hr />
<footer>
<p>© #DateTime.Now.Year - My ASP.NET Application</p>
</footer>
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>

By excluding the _layout file from the partial view, the script file was not firing as expected. After a lengthy conversation with Patrick Hume, I Created a _blank layout file (as below) and everything was working as expected. It's probably not the cleanest way to do this. But it worked.
_blank layout
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="container body-content">
#RenderBody()
</div>
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
#RenderSection("scripts", required: false)
</body>
</html>

Related

Pass the value of a button to a hidden field and save it to database

So my design is I have multiple display fields and one hidden field. Besides each row there are two buttons accept and reject.my point is when I click a button its value pass to the hidden field and submits automatically in the database.
when I try my code the button doesn't pass anything and I tried all the solutions related to this topic and nothing is working. what am I doing wrong?
controller:
[HttpGet]
public ActionResult Add_Fulfillment ()
{
var getData = db.TBL_Request.Include(x=>x.TBL_Accounts).Include(x=>x.TBL_Accounts_LOBs).ToList() ;
var add_fulfillment = new Add_Fulfillment();
var ful_ = new fulfillmentVM();
foreach (var data in getData)
{
List<Add_Fulfillment> fulfillment = db.TBL_Request.Select(i => new Add_Fulfillment
{
Request_ID = i.Request_ID,
Employee_no = i.Employee_no,
Operation_Date = i.Operation_Date,
Fulfillment_Rate = i.Fulfillment_Rate ??0,
Account_Name = i.TBL_Accounts.Account_Name,
LOB = i.TBL_Accounts_LOBs.LOB,
Status = i.Inserted_by
}).ToList();
ful_._Requests = fulfillment;
}
return View(ful_);
}
[HttpPost]
public ActionResult Add_Fulfillment_Accept(int Request_ID , int? Status)
{
var user= db.TBL_Request.Find(Request_ID);
//hiddenfieldvalue assigns it to the field in the database i want to update
db.SaveChanges();
return RedirectToAction("Add_Fulfillment");
}
[HttpPost]
public ActionResult Add_Fulfillment_Reject(int Request_ID)
{
return RedirectToAction("Add_Fulfillment");
}
the view
#model Staff_Requisition.Models.fulfillmentVM
#{
ViewBag.Title = "Add_Fulfillment";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Add_Fulfillment</h2>
<!-- page content -->
<div class="right_col" role="main">
<div class="">
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<div class="x_title">
<h2>Plain Page</h2>
<div class="clearfix"></div>
</div>
<div class="x_content">
<table class="table">
<tr>
<th>
Employee_no
</th>
<th>
Operation_Date
</th>
<th>
Fulfillment_Rate
</th>
<th>
Account_Name
</th>
<th>
LOB
</th>
<th></th>
<th></th>
</tr>
#for (int i = 0; i < Model._Requests.Count(); i++)
{
<tr>
<td>
#Html.DisplayFor(x => Model._Requests[i].Employee_no)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].Operation_Date)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].Fulfillment_Rate)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].Account_Name)
</td>
<td>
#Html.DisplayFor(x => Model._Requests[i].LOB)
</td>
<td>
#Html.Hidden("Status" , Model._Requests[i].Status , new { id = "myEdit" })
</td>
#using (Html.BeginForm("Add_Fulfillment_Accept", "TBL_Request", FormMethod.Post, new { #id = "myForm" }))
{
#Html.AntiForgeryToken()
<td>
<button id="btnAccept" class="btn btn-lg btn-success" name="a_button" type="submit" value="122">Accept</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
</td>
}
#using (Html.BeginForm("Add_Fulfillment_Reject", "TBL_Request", FormMethod.Post, new { #id = "myForm" }))
{
#Html.AntiForgeryToken()
<td>
<button id="btnReject" class="btn btn-lg btn-danger" name="button" type="submit" value="222">Reject</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
</td>
}
</tr>
}
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /page content -->
#section Scripts {
<script>
$("#btnAccept").click(function () {
$("#myEdit").val($("#btnAccept").val());
})
$("#btnReject").click(function () {
$("#myEdit").val($("#btnReject").val());
})
</script>
}
I solved it. the only issue was I didn't put the hidden field of the status inside the form .that's why it never passes the value. thank you for all your efforts though!
view:
#using (Html.BeginForm("Add_Fulfillment_Accept", "TBL_Request", FormMethod.Post))
{
#Html.AntiForgeryToken()
<td>
<button id="btnAccept" class="btn btn-lg btn-success" name="a_button" type="submit" onclick="accept(122)" value="122">Accept</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
#Html.Hidden("Status", Model._Requests[i].Status, new { id = "myEdit", value = "" })
</td>
}
#using (Html.BeginForm("Add_Fulfillment_Reject", "TBL_Request", FormMethod.Post))
{
#Html.AntiForgeryToken()
<td>
<button id="btnReject" class="btn btn-lg btn-danger" name="button" type="submit" onclick="reject(222)" value="222">Reject</button>
#Html.Hidden("Request_ID", Model._Requests[i].Request_ID)
#Html.Hidden("Status", Model._Requests[i].Status, new { id = "myEdit", value = "" })
</td>
}
</tr>
}
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /page content -->
#section Scripts {
<script>
$('[name = "a_button"]').click(function () {
$('[name = "Status"]').val($('[name = "a_button"]').val());
})
$('[name = "button"]').click(function () {
$('[name = "Status"]').val($('[name = "button"]').val());
})
</script>

I want to convert my view as it is in the picture to a downloadable pdf file in mvc, c#, or JS

[This] 1 is my view. After the button click, I want to embed this view as a picture or by HTML with CSS to a pdf file. This pdf file gets downloaded on button click.I tried lots of methods like itextsharp, jsPDF, phantomJS but I still have no clue how to achieve it. Can anyone help?
function start() {
var table = tableToJson($('#StudentInfoListTable').get(0))
var doc = new jsPDF('p', 'pt', 'a1', true);
doc.cellInitialize();
$.each(table, function (i, row) {
$.each(row, function (j, cell) {
doc.cell(10, 50, 120, 50, cell, i); // 2nd parameter=top margin,1st=left margin 3rd=row cell width 4th=Row height
})
})
doc.save('sample-file.pdf');
}
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace('/ /gi', '');
}
// go through cells
for (var i = 0; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j = 0; j < tableRow.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
body{
background: url("");
background-attachment: fixed;
background-repeat: no-repeat;
}
.content {
width: 100%;
min-height: 400px;
}
.box-header {
background-color: #838060;
height: 50px;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
color: white;
}
.box-header h4 {
position: relative;
top: 10px;
}
.box {
background-color: whitesmoke;
position: relative;
width: 100%;
font-size:28px;
}
.middle{
width:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<div class="card">
<div class="card-body">
<table cellpadding="30" class="table table-striped" id="StudentInfoListTable">
<tr>
<td><img src="#Model.img" alt="" height="200" width="200" /></td>
<td class="middle"></td>
<td>LICENSE ID - #Html.DisplayFor(m => m.LicenseID)</td>
</tr>
<tr>
<td>NAME: </td>
<td class="middle"></td>
<td>#Html.DisplayFor(m => m.Name)</td>
</tr>
<tr>
<td>#Html.DisplayFor(m => m.Relo) </td>
<td class="middle"></td>
<td>#Html.DisplayFor(m => m.careOf)</td>
</tr>
<tr>
<td>GENDER: </td>
<td class="middle"></td>
<td>#Html.DisplayFor(m => m.gender)</td>
</tr>
<tr>
<td>BLOOD GROUP: </td>
<td class="middle"></td>
<td>#Html.DisplayFor(m => m.blood)</td>
</tr>
<tr>
<td>DATE OF BIRTH: </td>
<td class="middle"></td>
<td>#Html.DisplayFor(m => m.date)</td>
</tr>
<tr>
<td>CONTACT NO: </td>
<td class="middle"></td>
<td>#Html.DisplayFor(m => m.Mobile)</td>
</tr>
<tr>
<td>ADDRESS: </td>
<td class="middle"></td>
<td>#Html.DisplayFor(m => m.Address)</td>
</tr>
<tr>
<td>Signature </td>
<td class="middle"></td>
<td><img src="#Model.sign" alt="" style="background-color:white;"/></td>
</tr>
</table>
<br/><br/>
<button onclick="start()" class="btn btn-block btn-primary">download</button>
</div>
</div>
Tried this way but doesn't render the CSS, instead it generates this see here.
You can Post the HTML string to server and convert it to PDF.
Here is the demo :
HTML : (Obviously you can use your existing HTML)
<div id="dvTable">
<table cellspacing="0" rules="all" border="1">
<tr>
<th scope="col" style="width: 120px;background-color:#D20B0C">
Customer Id
</th>
<th scope="col" style="width: 150px;background-color:#D20B0C">
Name
</th>
<th scope="col" style="width: 100px;background-color:#D20B0C">
Country
</th>
</tr>
<tr>
<td>
ALFKI
</td>
<td>
Maria Anders
</td>
<td>
Germany
</td>
</tr>
<tr>
<td>
ANATR
</td>
<td>
Ana Trujillo
</td>
<td>
Mexico
</td>
</tr>
</table>
</div>
<input type="hidden" id="hfTableHTML" name="Table_HTML" />
<hr />
<asp:Button Text="Export" runat="server" OnClick="Export" OnClientClick="SetHTML()" />
<script type="text/javascript">
function SetHTML() {
document.getElementById("hfTableHTML").value = document.getElementById("dvTable").innerHTML;
}
</script>
Namespaces:
using System.IO;
using System.Text;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
C# function:
protected void Export(object sender, EventArgs e)
{
//Export HTML String as PDF.
string html = Request.Form["Table_HTML"];
StringReader sr = new StringReader(html);
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Table.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
OR For MVC/C# you can use : Rotativa http://nuget.org/packages/Rotativa. It's based on wkhtmltopdf.
install it from nuget : Install-Package Rotativa -Version 1.7.3 and usage is simple :
public ActionResult PrintIndex()
{
return new ActionAsPdf("Index", new { name = "Giorgio" }) { FileName = "Test.pdf" };
}
You can define an action that returns an ActionResult of the type ActionAsPdf (RouteAsPdf is also available). where name = "Giorgio" is a route parameter.

how to add multiple of model in one view

I want to add my class model in my index view because I need ClassID for dropdown to show classes in my view but don't know how to.
This is my index:
#using opr.Models;
#using PagedList;
#using PagedList.Mvc;
#model PagedList.IPagedList<opr.Data.C_QuestionTable>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="alert-success form-control m-auto w-75 custom-form">
<div class="col-6 pb-3 input-control">
<label for="ex3"> Select Class:</label>
#Html.DropDownListFor(model => model.ClassID, (SelectList)ViewBag.dataForDropDowns, new { #class = "form-control select2ddl" })
</div>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
QuestionText
</th>
</tr>
#foreach (var item in Model)
{
foreach (var answer in item.C_AnswerTable)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.QuestionText)
#Html.RadioButton("searchBy", answer.Options, true)
<text>#answer.Options</text>
</td>
</tr>
}
}
<tr>
<div class="pagination pull-left">
<hr />
<td colspan="3">#Html.PagedListPager(Model, page => Url.Action("Index", new { page = page }))</td>
</div>
</tr>
</table>
</div>
This is my Controller:
examsEntities db = new examsEntities();
public ActionResult Index(int?page)
{
var mod1 = db.myclasses.Select(s => new { s.ID, s.C_name }).ToList();
SelectList sList = new SelectList(mod1, "ID", "C_name");
ViewBag.dataForDropDown = sList;
var pageNumber = page ?? 1;
var pageSize = 3;
var question = db.C_QuestionTable.OrderBy(x => x.QuestionText).ToPagedList(pageNumber, pageSize);
return View(question);
}
namespace OMS.Models
{
public class AbcModel
{
public int Id { get; set; }
public string Name{ get; set; }
public Classmodel classmodel{ get; set; }
}
}
bind class model into Index model(Abc model) and now in view
#using opr.Models;
#using PagedList;
#using PagedList.Mvc;
#model PagedList.IPagedList<opr.Data.C_QuestionTable>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div class="alert-success form-control m-auto w-75 custom-form">
<div class="col-6 pb-3 input-control">
<label for="ex3"> Select Class:</label>
#Html.DropDownListFor(model => model.classmodel.ClassID,
(SelectList)ViewBag.dataForDropDowns, new { #class = "form-control
select2ddl" })
</div>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
QuestionText
</th>
</tr>
#foreach (var item in Model)
{
foreach (var answer in item.C_AnswerTable)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.QuestionText)
#Html.RadioButton("searchBy", answer.Options, true)
<text>#answer.Options</text>
</td>
</tr>
}
}
<tr>
<div class="pagination pull-left">
<hr />
<td colspan="3">#Html.PagedListPager(Model, page => Url.Action("Index", new { page = page }))</td>
</div>
</tr>
</table>
</div>
Hope it will help you

How to bind JSON object with knockout on Dropdown change with html table

When I change the dropdown value, json data is change but not loads, and throws this error:
Uncaught Error: You cannot apply bindings multiple times to the same element.
How to resolve this?
$("#VehicleID").change(function () {
var categoryid = $("#VehicleTypeID option:Selected").val().trim();
var subcategoryid = $(this).val();
var url = "../Consignment/LoadratebydetailId";
$.getJSON(url, { CategoryID: categoryid, SubCategory: subcategoryid },
function (classesData) {
//var koNode = document.getElementById('fareDetailbody');
ko.cleanNode(classesData);
//ko.cleanNode($element[0]);
ko.applyBindings({
teams: classesData,
});
});
$("#rateChargeDiv").hide();
$("#rateChargeDiv").show();
});
<div id="rateDiv">
<div>
<h4>Selected Detail Changed</h4>
<table>
<thead>
<tr>
<th>name</th>
<th>cloth</th>
<th>color</th>
<th>size</th>
<th>length</th>
<th>total</th>
</tr>
</thead>
<tbody id="fareDetailbody" data-bind="foreach: teams">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: cloth"></td>
<td data-bind="text: color"></td>
<td data-bind="text: size"></td>
<td data-bind="text: length"></td>
<td data-bind="text: total"></td>
</tr>
</tbody>
</table>
</div>
<div id="close">close</div></div>
public JsonResult LoadratebydetailId(string CategoryID, string SubCategory)
{
if (CategoryID == "" || string.IsNullOrEmpty(CategoryID))
{
return Json("failure");
}
var vehCategory = this.GetratebydetailId(Convert.ToInt32(CategoryID));
var StatesData = vehCategory.
Where(cat => cat.VehicleCategoryID==Convert.ToInt32(SubCategory))
.Select(m => new
{
m.name,
m.cloth,
m.color,
m.size,
m.length,
m.total
});
return Json(StatesData, JsonRequestBehavior.AllowGet);
}

How to expand/collapse html table with partial view?

I am trying to expand/collapse a table row when a button is clicked. For the moment I can only expand the row.
I want to be able to collapse it aswell.
I am using a partial view.
I have tried this: expand/collapse table rows with JQuery but can't get it to work since I am loading data from a sql-database in a foreach loop.
To clarify: This expands the table, but I'm missing the collapse-part of my javascript code. Thanks in advance.
PartialView
<div class="table" id="logtable">
<div class="row">
<div class="cell" id="tableth">
message
</div>
</div>
#foreach (var item in Model.Logs)
{
<div class="row">
<div class="cell" id="tabletd">
<input type="button" name="answer" value="Show Div" onclick="showDiv(#item.id.ToString())" />
#Html.DisplayFor(modelItem => item.message)
</div>
</div>
<div class="row">
<div id="#item.id.ToString()" style="display:none;" class="answer_list">
<strong>Uri:</strong> #item.Uri <br/>
<strong>Method:</strong> #item.Method <br />
<strong>HttpStatus:</strong> #item.HttpStatus <br />
</div>
</div>
Javascript (in my HTML-view)
<script type="text/javascript">
function showDiv(message) {
document.getElementById(message).style.display = "block";
}
</script>
Do you want a toggle function? Check the status of the element and then chose whether to show or hide:
<script type="text/javascript">
function showDiv(message) {
if(document.getElementById(message).style.display == 'block'){
document.getElementById(message).style.display = "none";
}
else{
document.getElementById(message).style.display = "block";
}
}
</script>
Strictly speaking, this is pure javascript and not jQuery. If you really are using jQuery, you can make it even simpler:
function showDiv(message) {
$('#'+message).toggle();
}
You can even even go for a beautiful animation:
function showDiv(message) {
$('#'+message).slideToggle();
}
<style>
#dvExpoByBatchDate .expandExpo {
background-image: url("../Images/Expand.gif");
background-repeat: no-repeat;
background-position: center,center;
}
#dvExpoByBatchDate .expandExpoDisabled {
background-image: url("../Images/ExpandDisabled.gif");
background-repeat: no-repeat;
background-position: center,center;
}
#dvExpoByBatchDate .collapseExpo {
background-image: url("../Images/Collapse.gif");
background-repeat: no-repeat;
background-position: center,center;
}
</style>
//This is WrapperModel which contains all models for different level.
public class WrapperModel
{
public List<Employee> ListEmployee;
public List<Manger> Listmanger;
public List<Programmer> ListProgrammer;
}
#model Model.WrapperModel
<script>
//Default set to collapse Parent Header
$("#dtExposure .relationshipExposure").attr('colspan', 1);
//Hide child columns
$(".subRelationshipExposure").hide();
</script>
<style>
#dtExposure tr th {
cursor: default !important;
}
</style>
<table id="dtExposure" class="dbExposure display">
#if (Model != null)
{
if (Model.ListEmployee!= null) -- Parent Row View
{
#Html.Partial("Exposure/_ParentPartial", Model)
}
if (Model.Listmanger!= null) -- child Row View
{
#Html.Partial("Exposure/_ChildPartial", Model)
}
}
</table>
// Parent Partial View
#model Model.WrapperModel
<thead id="groupHead">
<tr>
<th rowspan="2" style="background-color: #003675"></th>
<th rowspan="2" style="background-color: #003675">ID</th>
<th class="relationshipExposure sorting_disabled" colspan="4" style="background-color: #003675">
FullName <span>&#9658</span>
</tr>
<tr>
#*HiddenSubChildColumn*#
<th style="background-color: #003675">FullName</th>
<th class="subRelationshipExposure" style="background-color: #003675">First Name</th>
<th class="subRelationshipExposure" style="background-color: #003675">Last Name</th>
<th class="subRelationshipExposure" style="background-color: #003675">Phone</th>
</tr>
</thead>
<tbody id="groupBody">
#foreach (var item in Model.ListEmployee)
{
<tr>
<td id="toggleExposureRelationship" class="expandExpo emptyTd" style="background-color:white;border:none"></td>
<td>#item.CDL</td>
<td>
<span id="relationshipExpo" style="color: #0000ff; cursor: pointer">#item.FullName</span>
</td>
<td class="subRelationshipExposure">#item.FirstName</td>
<td class="subRelationshipExposure">#item.LastName</td>
<td class="subRelationshipExposure">#item.Phone</td>
</tr>
}
</tbody>
//Child Partial View
#model Model.WrapperModel
<thead id="customHead">
<tr class="SubExposureCustomer" style="display: none">
<th class="emptyTd"></th>
<th style="background-color: #003675">ID#</th>
<th style="background-color: #003675">Full Name</th>
<th style="background-color: #003675" class="subRelationshipExposure">First Nmae</th>
<th style="background-color: #003675" class="subRelationshipExposure">Last Namen</th>
<th style="background-color: #003675" class="subRelationshipExposure">Phone</th>
</tr>
<tbody id="customBody">
#*Customer Level*#
#foreach (var item in Model.Listmanger)
{
var currCustomerMasterId = item.CUSTOMERMASTERID;
<tr class="SubExposureCustomer" data-currcustomermasterid="#currCustomerMasterId" style="display: none">
<td class="ExpoCustomerIcon expandExpo emptyTd" style="background-color:white;border:none"></td>
<td>#item.ID</td>
<td>#item.FULLNAME</td>
<td class="subRelationshipExposure">#item.FIRSTNAME</td>
<td class="subRelationshipExposure">#item.LASTNAME</td>
<td class="subRelationshipExposure">#item.PHONE</td>
</tr>
//For Pure MVC Grid Collapse
function ToggleExposure(“relationshipExposure”, “subRelationshipExposure”, 4) {
$(document).on("click", "." + className, function (e) {
var selfExposre = $("." + className);
var subSelfExposre = $("." + subclassName);
if (selfExposre.attr('colspan') == colspan) {
subSelfExposre.toggle();
selfExposre.attr('colspan', 1);
isCollpase = false;
}
else {
subSelfExposre.toggle();
selfExposre.attr('colspan', colspan);
isCollpase = true;
}
var varId = selfExposre.find("span");
varId.empty();
isCollpase ? varId.html("&#9668") : varId.html("&#9658");
});
}

Categories

Resources