i want to convert my gridview table into pdf - ajax

**when i tried to convert my grid-view data into PDF i got null reference exception grid-view header row but data is available in grid view.please help me to solve this error. i am using asp.net web API in this.. and i tried to on another grid-view to bind data..it shows same error null reference exception but when i tried on direct button click it works fine..only it shows error when i tried on using web API..please help me to solve this
i have attached my programming below data load and bind
public void GetData()
{
string conn = ConfigurationManager.ConnectionStrings["con"].ToString();
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlCommand cmd = new SqlCommand("select * from api", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "api");
//DataTable dta = new DataTable();
//dta = ds.Tables["api"];
//da.Fill(dta);
GridView2.DataSource = ds;
GridView2.DataBind();
}
convert to pdf
public string Button3_Click()
{
PdfPTable pdfTable = new PdfPTable(GridView2.HeaderRow.Cells.Count);
foreach (TableCell headercell in GridView2.HeaderRow.Cells)
{
iTextSharp.text.Font font = new iTextSharp.text.Font();
font.Color = new Basecolor(GridView2.HeaderRow.ForeColor);
PdfPCell pdfcell = new PdfPCell(new Phrase(headercell.Text, font));
pdfcell.BackgroundColor = new Basecolor(GridView2.HeaderStyle.BackColor);
pdfTable.AddCell(pdfcell);
}
foreach (GridViewRow gridviewrow in GridView2.Rows)
{
foreach (TableCell tablecell in gridviewrow.Cells)
{
iTextSharp.text.Font font = new iTextSharp.text.Font();
font.Color = new Basecolor(GridView2.RowStyle.ForeColor);
PdfPCell pdfcell = new PdfPCell(new Phrase(tablecell.Text));
pdfcell.BackgroundColor = new Basecolor(GridView2.RowStyle.BackColor);
pdfTable.AddCell(pdfcell);
}
}
Document pdfdoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
PdfWriter.GetInstance(pdfdoc, Response.OutputStream);
pdfdoc.Open();
pdfdoc.Add(pdfTable);
pdfdoc.Close();
Response.ContentType = "application/pdf";
Response.AppendHeader("content-disposition", "attachment;filename=Employyes.pdf");
Response.Write(pdfdoc);
Response.Flush();
Response.End();
return "success";
}
ajax function call
$(document).ready(function () {
$("#Button2").click(function () {
alert("ajax call");
$.ajax
({
method: "GET",
url: "api/Employees",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("success");
},
error: function (responce) {
alert("error");
},
});
});
});
<asp:Button ID="Button1" runat="server" Style="width: 136px" Text="Export to Excel" Width="175px" />&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<asp:Button ID="Button2" runat="server" Text="Export to PDF" Width="175px" />
<br />
<br />
<div class="auto-style1" id="NewData">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="true">
</asp:GridView>
</div>
here is my controller class
public class EmployeesController : ApiController
{
// success s = new success();
BusinessLogicLayer bal = new BusinessLogicLayer();
public string Get(string username, string password)
{
return bal.login(username, password);
}
[System.Web.Mvc.HttpPost]
public string POST(string firstname, string lastname, string username, string password, string email)
{
return bal.Register(firstname, lastname, username, password, email);
}
[System.Web.Http.HttpGet]
public string buttonclick()
{
// MessageBox.Show("come");
return bal.ExportConvert();
}
here is my business logic layer class method
public string ExportConvert()
{
success s = new success();
return s.Button3_Click();
}[enter image description here][1]
here my login page code
**<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body style="padding-top:20px;">
<div class="col-md-10 col-md-offset-1">
<div class="well">
<table class="table table-bordered">
<thead>
<tr class="success">
<th colspan="2">
Existing User Login
<a class="btn btn-success pull-right" href="Registration.html">Register</a>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>UserName</td>
<td>
<input type="text" id="username" placeholder="username"/>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" id="password" placeholder="Password" />
</td>
</tr>
<tr class="success">
<td colspan="2">
<input type="button" id="btnlogin" class="btn btn-success" value="login" />
</td>
</tr>
</tbody>
</table>
<div class="modal fade" tabindex="-1" id="successmodel"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4>Success</h4>
</div>
<div class="modal-body">
<h2>Registraton success</h2>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-success">
Close
</button>
</div>
</div>
</div>
</div>
<div id="divError" class="alert alert-danger collapse">
<a id="linkClose" class="close" href="#" >×</a>
<div id="divErrorText"></div>
</div>
</div>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script type="text/javascript" >
$(document).ready(function () {
$('#linkClose').click(function () {
$('divError').hide('fade');
})
});
$('#btnlogin').click(function () {
$.ajax({
url: '/api/Employees/?username=' + $("#username").val() + '&password=' + $("#password").val(),
method: 'Get',
contentType: 'application/json',
data: { id: 1 },
dataType: 'json',
success: function (data) {
console.log(data);
//var data = data.d;
//alert("success " + data);
if (data == 'success') {
window.location = "/success.aspx";
}
else {
alert("Wrong Username and Password");
}
/* if (data != null) {
$.each(data, function (i, obj) {
var c = new WorkflowsEntity(data[i]); //logic
self.WorkflowList.push;
});
alert("success");
//window.location.href = "/success.html";
}*/
},
error: function (jqXHR, textStatus, errorThrown) {
alert(" un correct username password ");
$('#divErrorText').text(jqXHR.responceText);
$('#divError').show('fade');
}
});
});
</script>
</body>
</html>**

Related

how to Upload files with progress bar in Ajax with asp.net core

I wrote the file upload codes with Ajax and they work fine, but I could not write the percentage of file upload progress. I want to use a progress bar for the percentage of progress. Please write a sample of my code with the progress bar. Thanks
I wrote the file upload codes with Ajax and they work fine, but I could not write the percentage of file upload progress. I want to use a progress bar for the percentage of progress. Please write a sample of my code with the progress bar. Thanks
<td class="d-flex justify-content-around">
<div>
<label asp-for="mostanadPath" class="btn btn-outline-info">
انتخاب تصویر
<span class="oi oi-file h5 text-dark"></span>
</label>
<span class="text-center mt-2" id="spnImageCartMlie" style="color: black;font-size: 12px"></span>
</div>
<div>
<input type="button" onclick="UploadImage()" value="آپلود فایل" class="btn btn-outline-danger" id="btnUpLoad" />
<div id="divmessage" class="text-center hidden m-2"></div>
<input class="d-none" value="#ViewBag.proID" name="id" />
</div>
<input id="newCartMlieImagePathName" name="newCartMlieImagePathName" hidden />
<input id="mostanadPath" asp-for="mostanadPath" type="file" class="d-none">
<div class="mt-5 col-6">
<div class="progress">
<div class="progress-bar progress-bar-success progress-bar-striped
active" role="progressbar"
aria-valuemin="0" aria-valuemax="100" style="width:0%">0%</div>
</div>
</div>
</td>
<script>
$("#mostanadPath").change(function () {
var filename = this.files[0].name;
$("#spnImageCartMlie").html(filename);
});
</script>
<script>
var UploadImage = function () {
var data = new FormData;
var file = $("#mostanadPath").get(0);
var files = file.files;
//کنترل سایز فایل
if (files[0].size >= 5120000) {
$("#spnImageCartMlie").removeClass('hidden');
$("#spnImageCartMlie").text('حجم فایل بیش از 500 کیلوبایت است');
$("#spnImageCartMlie").css("color", "red");
return false;
}
for (var i = 0; i < files.length; i++) {
data.append('filearray', files[i]);
data.append('filesize', files[i].size);
}
data.append('path', "img\\mostandat\\");
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.progress-bar').width(percentComplete + '%');
$('.progress-bar').html(percentComplete + '%');
}
}, false);
return xhr;
},
url: '#Url.Action("UploadImageFile", "Project")',
type: "POST",
data: data,
contentType: false,
processData: false }).done(function (result) {
if (result.status == "success") {
toastr.success('فایل با موفقیت آپلود شد', {
timeOut: 2000,
closeButton: true,
});
$("#newCartMlieImagePathName").val(result.imagename);
}
}).fail(function (result) {
if (result.status != "success") {
toastr.warning('در حین آپلود مشکلی بوجود آمد', {
timeOut: 2000,
closeButton: true,
});
}
});
}
</script>
public IActionResult UploadImageFile(IEnumerable<IFormFile> filearray, String path)
{
String fileName = _uploadFiles.UploadFilesFunc(filearray, path);
return Json(new { status = "success", imagename = fileName });
}
You can use this JQuery code in your <script>:
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.progress-bar').width(percentComplete+'%');
$('.progress-bar').html(percentComplete+'%');
}
}, false);
return xhr;
},
url: yoururl,
type: "POST",
data: data,
contentType: false,
processData: false
success: function(result) {
console.log(result);
}
});
and Add this code in your page
<div class="progress">
<div class="progress-bar progress-bar-success progress-bar-striped
active" role="progressbar"
aria-valuemin="0" aria-valuemax="100" style="width:0%">0%</div>
</div>
then you can see the progress bar when you upload file.
===============================================
If you want only one button,you can use this code:
<input type="file" id="files" />
<script>
$("#files").change(function () {
$.ajax({
//........
});
})
</script>
=================================================
I just add the code I gave you above to ajax
<div class="container mt-4 col-2">
<table class="table table-bordered">
<tbody class="text-center">
<tr>
<td>
<label asp-for="mostanadPath" class="btn btn-outline-info">
Image selection
<span class="oi oi-file h5 text-dark"></span>
</label>
</td>
</tr >
<tr>
<td>
<span class="text-center" id="spnImageCartMlie" style="color: black;font-size: 12px"></span>
<input id="newCartMlieImagePathName" name="newCartMlieImagePathName" hidden />
</td>
</tr>
<tr>
<td>
<input type="button" onclick="UploadImage()" value="Upload and display the image" class="btn btn-outline-danger" id="btnUpLoad" />
</td>
</tr>
<tr>
<td>
<div id="divmessage" class="text-center hidden"></div>
</td>
</tr>
</tbody>
</table>
<input asp-for="mostanadPath" type="file" class="d-none" >
</div>
<div class="progress">
<div class="progress-bar progress-bar-success progress-bar-striped
active" role="progressbar"
aria-valuemin="0" aria-valuemax="100" style="width:0%">0%</div>
</div>
#section Scripts {
<script>
$("#mostanadPath").change(function () {
var filename = this.files[0].name;
$("#spnImageCartMlie").html(filename);
});
</script>
<script>
var UploadImage = function () {
var data = new FormData;
var file = $("#mostanadPath").get(0);
var files = file.files;
//File size control
if (files[0].size >= 512000) {
$("#spnImageCartMlie").removeClass('hidden');
$("#spnImageCartMlie").text('The file size is more than 500 KB');
$("#spnImageCartMlie").css("color", "red");
return false;
}
for (var i = 0; i < files.length; i++) {
data.append('filearray', files[i]);
data.append('filesize', files[i].size);
}
data.append('path', "img\\mostandat\\");
$.ajax({
//add here......
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
$('.progress-bar').width(percentComplete+'%');
$('.progress-bar').html(percentComplete+'%');
}
}, false);
return xhr;
},
type: "post",
url: '/Home/UploadImageFile',
data: data,
contentType: false,
processData: false
}).done(function (result) {
if (result.status == "success") {
$("#divmessage").text("Upload was successful.");
$("#divmessage").css("color", "green");
$("#divmessage").removeClass("hidden");
$("#newCartMlieImagePathName").val(result.imagename);
}
}).fail(function (result) {
if (result.status != "success") {
$("#divmessage").css("color", "red");
$("#divmessage").removeClass("hidden");
$("#divmessage").text("There was a problem uploading.");
}
});
}
</script>
}

How can I refresh my partial view on my parent index after a modal update to add new information?

I am certain this question has been asked before, I don't think there is anything unique about my situation but let me explain. I have my Index View (Parent), on that Index View there is a partial View Dataset Contacts "links" (child), I have an Add Contact button, which pops a Modal and allows me to submit the form data to add to the database, when I return I want to only refresh the partial view of links. Note: the Controller Action Dataset_Contacts below needs to fire in order to refresh the partial view (child). It might go without saying, but I don't see this happening with my current code. Any assistance will be appreciated.
on my Index View index.cshtml I have the following code to render my partial View
<div class="section_container2">
#{ Html.RenderAction("Dataset_Contacts", "Home"); }
</div>
Here is the controller:
[ChildActionOnly]
public ActionResult Dataset_Contacts()
{
// Retrieve contacts in the Dataset (Contact)
//Hosted web API REST Service base url
string Baseurl = "http://localhost:4251/";
var returned = new Dataset_Contact_View();
var dataset = new Dataset();
var contacts = new List<Contact>();
var contact_types = new List<Contact_Type>();
using (var client = new HttpClient())
{
dataset = JsonConvert.DeserializeObject<Dataset>(datasetResponse);
contact_types = JsonConvert.DeserializeObject<List<Contact_Type>>(ContactTypeResponse);
// Set up the UI
var ds_contact = new List<ContactView>();
foreach (Contact c in dataset.Contact)
{
foreach (Contact_Type t in contact_types)
{
if (c.Contact_Type_ID == t.Contact_Type_ID)
{
var cv = new ContactView();
cv.contact_id = c.Contact_ID;
cv.contact_type = t.Description;
returned.Dataset_Contacts.Add(cv);
}
}
}
}
return PartialView(returned);
}
Here is my Partial View Dataset_Contacts.cshtml
#model ResearchDataInventoryWeb.Models.Dataset_Contact_View
<table>
#{
var count = 1;
foreach (var ct in Model.Dataset_Contacts)
{
if (count == 1)
{
#Html.Raw("<tr>")
#Html.Raw("<td>")
<span class="link" style="margin-left:10px;">#ct.contact_type</span>
#Html.Raw("</td>")
count++;
}
else if (count == 2)
{
#Html.Raw("<td>")
<span class="link" style="margin-left:300px;">#ct.contact_type</span>
#Html.Raw("</td>")
#Html.Raw("</tr>")
count = 1;
}
}
}
</table>
Also on my Index.cshtml is my Add Contact button, which pops a modal
<div style="float:right;">
<span class="link" style="padding-right:5px;">Add</span>
</div>
jquery for the Modal:
var AddContact = function () {
var url = "../Home/AddContact"
$("#myModalBody").load(url, function () {
$("#myModal").modal("show");
})
};
Controller action for AddContact
public ActionResult AddContact()
{
return PartialView();
}
Modal for AddContact.cshtml
#model ResearchDataInventoryWeb.Models.Contact
<form id="contactForm1">
<div class="section_header2">Contact</div>
<div style="padding-top:5px;">
<table>
<tr>
<td>
<span class="display-label">UCID/Booth ID</span>
</td>
<td>
#Html.TextBoxFor(model => model.Booth_UCID, new { placeholder = "<Booth/UCID>", #class = "input-box" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Type</span>
</td>
<td>
<select class="input-box" id="contact_type">
<option value="contact_type">Contact Type*</option>
<option value="dataset_admin">Dataset Admin</option>
<option value="dataset_Provider">Dataset Provider</option>
<option value="department">Department</option>
<option value="external_collaborator">External Collaborator</option>
<option value="principal_investigator">Principal Investigator</option>
<option value="research_center">Research Center</option>
<option value="vendor">Vendor</option>
</select>
</td>
</tr>
<tr>
<td>
<span class="display-label">Name</span>
</td>
<td>
#Html.TextBoxFor(model => model.First_Name, new { placeholder = "<First Name>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Last_Name, new { placeholder = "<Last Name>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Email</span>
</td>
<td>
#Html.TextBoxFor(model => model.Email, new { placeholder = "<Email 1>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Email_2, new { placeholder = "<Email 2>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Phone</span>
</td>
<td>
#Html.TextBoxFor(model => model.Phone_Number, new { placeholder = "<Phone 1>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Phone_Number_2, new { placeholder = "<Phone 2>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Job Title</span>
</td>
<td>
#Html.TextBoxFor(model => model.Title_Role, new { placeholder = "<Job Title>", #class = "input-box" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Organization</span>
</td>
<td>
<input class="input-box" type="text" placeholder="<Organization>" />
</td>
</tr>
</table>
<div style="padding-left:10px; margin-top:10px;">
<textarea rows="3" placeholder="Notes"></textarea>
</div>
</div>
<div class="centerButton" style="margin-top: 30px;">
<div style="margin-left:30px">
<submit id="btnSubmit" class="btn btn-default btn-sm" style="padding:14px"><span class="smallText_red" style="padding:30px">SAVE</span></submit>
</div>
<div style="margin-left:30px">
<submit class="btn btn-default btn-sm" style="padding:14px"><span class="smallText_red" style="padding:30px">REMOVE</span></submit>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
var frm = $('#contactForm1').serialize()
$.ajax({
type: "POST",
url: "/Home/AddContact/",
data: frm,
success: function () {
$("#myModal").modal("hide");
}
})
})
})
</script>
and lastly Action for [HttpPost] AddContact(Contact data)
[HttpPost]
public ActionResult AddContact(Contact data)
{
// Update the Database here
return View();
}
My solution:
1. Change ActionResult to JsonResult
{
// Update the Database code
// END
return Json(new
{
dbUpdateResult = "success"
});
}
2. In Ajax:
//Ajax code
...
success: function (ajaxRespond) {
if(ajaxRespond.dbUpdateResult == "success"){
$("#myModal").modal("hide");
reloadTable()
}
}
Then you can use 1:
function reloadTable(){
$('#CONTAINER_ID').load('#Url.Action("Dataset_Contacts", "Home")');
}
Or 2:
function reloadTable(){
let myurl = '#Url.Action("Dataset_Contacts", "Home")';
$.ajax({
type: "GET",
url: myurl,
success: function (data, textStatus, jqXHR) {
$("#CONTAINER_ID").html(data);
},
error: function (requestObject, error, errorThrown) {
console.log(requestObject, error, errorThrown);
alert("Error: can not update table")
}
});
}
So you reload your partial view after successful dbupdate. Please tell me, if I'm wrong...

Asp.Net Mvc Html.BeginFormSubmit ajax sends twice request (one's type xhr the other's document)

I am working on a survey application with Asp.Net MVC. I have a page named Index.cshtml which has a question table and a 'Add New' button.Once button clicked, a popup is opened with jQuery. I am calling a view from controller to fill jQuery dialog named as AddOrEdit.cshtml (child page). I am adding new question and options. Question is a textfield and its options are added in editable table. Once clicked submt button Submit form event (save or update) is fired. But ajax sends twice request. One of these requests send empty object, the other sends full object. Where am I making a mistake?
According to my research, what causes this problem is that the unobtrusive validator is placed on 2 different pages. But this is not the case for me.
When I debug with chrome in f12, the initiator of one of the 2 requests 'jquery' the initiator of the other 'other' The type of one of these 2 post requests appears as 'XHR' and the type of the other is 'document'.
Index.cshtml
#{
ViewBag.Title = "Soru Listesi";
}
<h2>Soru Oluşturma</h2>
<a class="btn btn-success" style="margin-bottom: 10px"
onclick="PopupForm('#Url.Action("AddOrEdit","Question")')"><i class="fa fa-plus"></i> Yeni Soru Oluştur</a><table id="questionTable" class="table table-striped table-bordered accent-blue" style="width: 100%">
<thead>
<tr>
<th>Soru No</th>
<th>Soru Adı</th>
<th>Oluşturma Tarihi</th>
<th>Güncelleme Tarihi</th>
<th>Güncelle/Sil</th>
</tr>
</thead>
</table>
<link
href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
rel="stylesheet" />
#section Scripts{
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function() {
dataTable = $("#questionTable").DataTable({
"ajax": {
"url": "/Question/GetData",
"type": "GET",
"datatype": "json"
},
"columnDefs": [
{ targets: 2 }
],
"scrollX": true,
"scrollY": "auto",
"columns": [
{ "data": "QuestionId" },
{ "data": "QuestionName" },
{
"data": "CreatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "UpdatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "QuestionId",
"render": function(data) {
return "<a class='btn btn-primary btn-sm' onclick=PopupForm('#Url.Action("AddOrEdit", "Question")/" +
data +
"')><i class='fa fa-pencil'></i> Güncelle</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete(" +
data +
")><i class='fa fa-trash'></i> Sil</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
}
],
"language": {
"emptyTable":
"Soru bulunamadı, lütfen <b>Yeni Soru Oluştur</b> butonuna tıklayarak yeni soru oluşturunuz. "
}
});
});
function getDateString(date) {
var dateObj = new Date(parseInt(date.substr(6)));
let year = dateObj.getFullYear();
let month = (1 + dateObj.getMonth()).toString().padStart(2, '0');
let day = dateObj.getDate().toString().padStart(2, '0');
return day + '/' + month + '/' + year;
};
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function(response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: true,
title: 'Soru Detay',
modal: true,
height: 'auto',
width: '700',
close: function() {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
debugger;
if (form.checkValidity() === false) {
debugger;
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.OptionId = row.find("TD").eq(0).html();
option.OptionName = row.find("TD").eq(1).html();
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err.data);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}
function ResetForm(form) {
Popup.dialog('close');
return false;
}
function Delete(id) {
if (confirm('Bu soruyu silmek istediğinizden emin misiniz?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Question")/' + id,
success: function(data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message,
{
className: "success",
globalPosition: "top center",
title: "BAŞARILI"
})
}
}
});
}
}
</script>
}
AddOrEdit.cshtml
#using MerinosSurvey.Models
#model Questions
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEdit", "Question", FormMethod.Post, new { #class = "needs-validation",
novalidate = "true", onsubmit = "return SubmitForm(this)", onreset = "return ResetForm(this)", id =
"questionForm" }))
{
<div class="form-group row">
#Html.Label("QuestionId", "Soru No", new { #class = "col-form-label col-md-3" })
<div class="col-md-9">
#Html.TextBoxFor(model => model.QuestionId, new { #readonly = "readonly", #class = "form-control" })
</div>
</div>
<div class="form-group row">
#Html.Label("QuestionName", "Soru Adı", new { #class = "col-form-label col-md-3" })
<div class="col-md-9">
#Html.EditorFor(model => model.QuestionName, new { htmlAttributes = new { #class = "form-control", required = "true" } })
<div class="valid-feedback"><i class="fa fa-check">Süpersin</i></div>
<div class="invalid-feedback "><i class="fa fa-times"></i></div>
</div>
</div>
#*<div class="form-group row">
#Html.LabelFor(model => model.CreatedDate, new { #class = "form-control-label col-md-3"})
<div class="col-md-9">
#Html.EditorFor(model => model.CreatedDate, "{0:yyyy-MM-dd}", new { htmlAttributes = new { #class = "form-control", type = "date", #readonly = "readonly",required="false" } })
</div>
</div>*#
<div class="table-wrapper form-group table-responsive-md">
<div class="table-title">
<div class="form-group row">
<div class="col-md-9">Seçenekler</div>
<div class="col-md-3">
<a class="btn btn-success add-new" style="margin-bottom: 10px"><i class="fa fa-plus"></i>Seçenek Ekle</a>
</div>
</div>
</div>
<table class="table optionTable">
<thead>
<tr>
<th scope="col">Seçenek Id</th>
<th scope="col">Seçenek Adı</th>
<th scope="col">Güncelle/Sil</th>
</tr>
</thead>
<tbody>
#*#foreach (Options options in Model.Options)
{
<tr>
<td>#options.OptionId</td>
<td>#options.OptionName</td>
<td>
<a class="add btn btn-primary btn-sm" title="Add" data-toggle="tooltip">
<i class="fa fa-check">Onayla</i></a>
<a class="edit btn btn-secondary btn-sm" title="Edit" data-toggle="tooltip"><i class="fa fa-pencil">Güncelle</i></a>
<a class="delete btn-danger btn-sm" title="Delete" data-toggle="tooltip"><i class="fa fa-trash">Sil</i></a>
</td>
</tr>
}*#
</tbody>
</table>
</div>
<div class="form-group row">
<input type="submit" value="Submit" class="btn btn-primary" id="btnSubmit" />
<input type="reset" value="Reset" class="btn btn-secondary" />
</div>
}
<script>
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
//var actions = $("table.optionTable td:last-child").html();
var actions =' <a class="add btn btn-primary btn-sm" title="Add" data-toggle="tooltip"><i
class="fa fa-check">Onayla</i></a>' + '<a class="edit btn btn-secondary btn-sm" title="Edit" data toggle="tooltip"><i class="fa fa-pencil">Güncelle</i></a>' +'<a class="delete btn-danger btn-sm" title="Delete" data-toggle="tooltip"><i class="fa fa-trash">Sil</i></a>';
// Append table with add row form on add new button click
$(".add-new").click(function () {
$(this).attr("disabled", "disabled");
var index = $("table.optionTable tbody tr:last-child").index();
var row = '<tr>' +
'<td><input type="text" class="form-control" name="optionId" id="optionId"></td>' +
'<td><input type="text" class="form-control" name="optionId" id="optionName"></td>' +
'<td>' + actions + '</td>' +
'</tr>';
$("table.optionTable").append(row);
$("table.optionTable tbody tr").eq(index + 1).find(".add, .edit").toggle();
$('[data-toggle="tooltip"]').tooltip();
});
// Add row on add button click
$(document).on("click", ".add", function () {
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
input.each(function () {
if (!$(this).val()) {
$(this).addClass("error");
empty = true;
} else {
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if (!empty) {
input.each(function () {
$(this).parent("td").html($(this).val());
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").removeAttr("disabled");
}
});
// Edit row on edit button click
$(document).on("click", ".edit", function () {
$(this).parents("tr").find("td:not(:last-child)").each(function () {
$(this).html('<input type="text" class="form-control" value="' + $(this).text() + '">');
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").attr("disabled", "disabled");
});
// Delete row on delete button click
$(document).on("click", ".delete", function () {
debugger;
$(this).parents("tr").remove();
$(".add-new").removeAttr("disabled");
});
});
event.preventDefault(); move this line and place it immediately after function SubmitForm (form){
Like below:
function SubmitForm(form) {
debugger;
event.preventDefault();
if (form.checkValidity() === false) {
debugger;
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.OptionId = row.find("TD").eq(0).html();
option.OptionName = row.find("TD").eq(1).html();
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err.data);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}

Deleting using Entity Framework and calling controller method in ajax

I have been trying to create a delete button in mvc using json to call the delete method in my controller but so far its not working.
I did trap the error alert in the script and the success section is not registering a thing, I need help well here is my view, that picks data from SQL Server using Entity Framework 5.1.
I am working with a table called Departments and it has two columns, DepartmentId and DepartmentName.
<div class="container" style="width:40%; margin-top:2%;">
<hr />
<table class="table-responsive">
<tr>
<th>Deprtment Name</th>
<th></th>
</tr>
<tbody>
#if(ViewBag.RowDepartmentList != null)
{
foreach(var item in ViewBag.RowDepartmentList)
{
<tr id="row_#item.DepartmentId">
<td>#item.DepartmentId</td>
<td>#item.DepartmentName</td>
<td><a href="#" class="btn btn-danger" onclick="ConfirmDelete(#item.DepartmentId)">
<i class="glyphicon glyphicon-trash"></i></a></td>
</tr>
}
}
</tbody>
</table>
<input type="hidden" id="HiddenDepartmentId" />
</div>
I added a hidden attribute to capture the DepartmentId, the form too has a delete button that first calls a delete dialog modal.
My DELETE dialog modal code:
<div class="modal fade" id="mymodal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" style="width:350px;">
<div class="modal-content">
<div class=" modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="close">
<span aria-hidden="true">x</span>
</button>
<h3 class="modal-title">Delete record</h3>
</div>
<div class="modal-body">
<h4>Are you sure you want to delete this?</h4>
</div>
<div class="modal-footer">
Cancel
Delete
</div>
</div>
</div>
And this is what my controller looks like:
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult DepartmentIndex()
{
MVCTutorialEntities2 db = new MVCTutorialEntities2();
List<EmployeeViewModel> emlist = db.Departments.Where(x => x.IsDeleted == 0).Select(x => new EmployeeViewModel {DepartmentId=x.Departmentid, DepartmentName = x.DepartmentName }).ToList();
ViewBag.RowDepartmentList = emlist;
return View();
}
// the delete function
[HttpPost]
public JsonResult DelDepartment(int depId)
{
MVCTutorialEntities2 db = new MVCTutorialEntities2();
bool result = false;
Department dep = db.Departments.SingleOrDefault(x => x.Departmentid == depId);
if (dep != null)
{
db.Departments.Remove(dep); // I don't know why this is not deleting .... the table is not cascaded
db.SaveChanges();
result = true;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
}
// now my script is all here that calls the
<script>
var ConfirmDelete = function (DepartmentId) {
$("#HiddenDepartmentId").val(DepartmentId);
$("#mymodal").modal("show");
}
var DelDepartment = function ()
{
var depId = $("#HiddenDepartmentId").val();
$.ajax({
type: 'POST',
url: 'Employee/DelDepartment',
data: { DepartmentId: depId },
success: function (result) {$("#mymodal").modal("hide"); },
error: function (result) { alert(result); $("#mymodal").modal("hide"); } // only the error section resturns a message of [object] of [object]
});
}
</script>
Trying so hard to learn this language ... and if so, is there any way I can just use razor and call the delete function from the
#using (Html.BeginForm("", "",FormMethod.POST)) ?
function?
data: { DepartmentId: depId } needs to be
data: { depId: depId } because the left JS parameter name has to match up with the parameter name on the controller side.
Or you may need to do: data: JSON.stringify({ depId: depId })
If that doesn't work, you can do url: 'Employee/DelDepartment?depId=' + deptId and just get rid of the data property altogether.

Get database record using AJAX, Knockout and JSON

I am fairly new to Knockout and Entity Framework and I have a problem where I cannot seem to output any JSON from an MVC 4 controller action via an AJAX call using Knockout onto an html page.
The table includes fields Email and RegsitrationNumber, these are used to validate the user.
If the user exists in the table then their country is displayed on the screen.
The profiler states a Status Code of 200 i.e OK. Can anyone help?
HTML ------
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="./Scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<div>
<div>
<h2 id="title">Login</h2>
</div>
<div>
<label for="email">Email</label>
<input data-bind="value: $root.Email" type="text" title="Email" />
</div>
<div>
<label for="registrationnumber">Registration Number</label>
<input data-bind="value: $root.RegistrationNumber" type="text" title="RegistrationNumber" />
</div>
<div>
<button data-bind="click: $root.login">Login</button>
</div>
</div>
<table id="products1" data-bind="visible: User().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
<script src="./Scripts/knockout-2.2.0.js"></script>
<script src="./Scripts/knockout-2.2.0.debug.js"></script>
<script src="./Scripts/functions.js"></script>
</body>
</html>
JAVASCRIPT -----
function UserViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Name = ko.observable("Robbie");
self.Email = ko.observable("rob#test.com");
self.Occupation = ko.observable("Designer");
self.Country = ko.observable("UK");
self.RegistrationNumber = ko.observable("R009");
self.UserDate = ko.observable("06-04-2014");
var User = {
Name: self.Name,
Email: self.Email,
Occupation: self.Occupation,
Country: self.Country,
RegistrationNumber: self.RegistrationNumber,
UserDate: self.UserDate
};
self.User = ko.observable(); //user
self.Users = ko.observableArray(); // list of users
//Login
self.login = function ()
{
alert("login");
if (User.Email() != "" && User.RegistrationNumber() != "") {
$.ajax({
url: '/Admin/Login',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(User),
success: function (data) {
self.Users.push(data);
$('#title').html(data.Email);
}
}).fail(
function (xhr, textStatus, err) {
console.log('fail');
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
} else {
alert('Please enter an email and registration number');
}
};
}
var viewModel = new UserViewModel();
ko.applyBindings(viewModel);
ACTION -----
public ActionResult Login(string Email, string RegistrationNumber)
{
var user = from s in db.Users
select s;
user = user.Where(s => s.Email.ToUpper().Equals(Email.ToUpper())
&& s.RegistrationNumber.ToUpper().Equals(RegistrationNumber.ToUpper())
);
if (user == null)
{
return HttpNotFound();
}
return Json(user, JsonRequestBehavior.AllowGet);
}
Looks like your binding is incorrect...
<table id="products1" data-bind="visible: Users().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
User().length should be Users().length.

Resources