I am trying to set the source of my datatable to the data returned from my stored procedure. This is my code, but my DataTable is not populated. Can someone please assist me with updating this code so the DataTable is populated with the stored procedure results?
This is my JavaScript
$("#btnClick").click(function () {
$('#example').DataTable({
ajax: {
url: getURL,
method: "GET"
},
columns: [
{ data: "Location" },
{ data: "TC" }
]
});
});
This is my HTML
<div id="table1">
<table id="example" class="display">
</table>
</div>
<br />
<div class="text-center">
<div class="btn-group">
<button type="button" id="btnClick">Button One</button>
</div>
</div>
#section Scripts {
<script>
var getURL = '#Url.Action("GTC")';
</script>
}
This is my Controller Code:
[ApiController]
[Route("api/EmpCheck")]
public class EmpCheckController : Controller
{
EmpCheck _context;
public EmpCheckController( context)
{
_context = context;
}
public IActionResult Index()
{
var VerifyAllEmpsOnDuty = _context.EmpCheckModel.FromSql("_GetClockedInEmps").ToList();
return View(VerifyAllEmpsOnDuty);
}
}
You can directly bind ajax source to datatable. if your API is working fine.
you can do it by two way.
1- directly bind ajax source.
2- fetch record using ajax and then bind response to DataTable.
Here is working example for both
Please check this one For more details Click here
cshtml page
<div id="table1">
<table id="example" class="display">
</table>
</div>
<br />
<div class="text-center">
<div class="btn-group">
<button type="button" id="btnClick">Button One</button>
</div>
</div>
Controller Code
[ApiController]
[Route("api/EmpCheck")]
public class EmpCheckController : Controller
{
EmpCheck _context;
public EmpCheckController( context)
{
_context = context;
}
public IActionResult Index()
{
return View();
}
public IActionResult LoadDataTable()
{
var VerifyAllEmpsOnDuty = _context.EmpCheckModel.FromSql("_GetClockedInEmps").ToList();
return Json(new
{
recordsTotal = VerifyAllEmpsOnDuty.Count(),
data = VerifyAllEmpsOnDuty
}, JsonRequestBehavior.AllowGet);
}
}
Javascript code
#section Scripts {
<script>
$( document ).ready(function() {
console.log( "ready!" );
var getURL = '#Url.Action("LoadDataTable","EmpCheck")';
This is my JavaScript
$("#btnClick").click(function () {
$('#example').DataTable({
ajax: {
url: getURL,
method: "GET"
},
columns: [
{ data: "Location" },
{ data: "TC" }
]
});
});
});
</script>
}
Related
I am attempting to use partial views for the first time and I need some help. I am posting a string from Javascript to my ASP controller so that I can query my database using that string. Like so:
JavaScript
function findEmployees(userCounty) {
$.ajax({
type: "POST",
url: '#Url.Action("Index", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
error: function (e) {
console.log(e)
console.log("error")
}
});
}
Controller
[HttpPost]
public ActionResult Index([FromBody]string userCounty)
{
string county = userCounty.Substring(0, userCounty.IndexOf(" "));
var query = from SOP in _context.SalesOffice_Plant
where SOP.County == county
select new SalesOffice_Plant
{
Employee = SOP.Employee
};
return PartialView(query.ToList());
}
[HttpGet]
public ActionResult Index()
{
ViewData["Title"] = "Contact Us";
ViewBag.Current = "Contact";
return View();
}
When I set break points - I can see that the string is passed correctly and my LINQ query works just fine. My problem occurs when I want to render a table of the employees in my Index page. The JavaScript returns a value to the controller after the page loads. This means I needed a way to "refresh the page". I was told to use a partial view to solve this problem and this is what I came up with.
Index.cshtml
#model IEnumerable<Project.Models.SalesOffice_Plant>
//A bunch of Html
#await Html.PartialAsync("_IndexPartial")
//More Html
_IndexPartial.cshtml
#model IEnumerable<Project.Models.SalesOffice_Plant>
<table class="table">
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Employee)
</td>
</tr>
}
</tbody>
Ideally, I would like a table of Employees to be generated and displayed in the Index.cshtml. However, when I load the page I get and error telling me that my #await Html.PartialAsync("_IndexPartial") 'is not set to an instance of an object.
Any pointers in the right direction would be very helpful.
When you use ajax,it would not reload your page after backend code finishing,so you need to use .html() method to render the backend result to html.
Here is a whole working demo:
Model:
public class SalesOffice_Plant
{
public int Id { get; set; }
public string County { get; set; }
public string Employee { get; set; }
}
View(Index.cshtml):
<button type="button" onclick="findEmployees('a ')">Find</button>
<div id="employee">
</div>
#section Scripts
{
<script>
function findEmployees(userCounty) {
$.ajax({
type: "POST",
url: '#Url.Action("Index", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
error: function (e) {
console.log(e)
console.log("error")
},
success: function (res) {
$("#employee").html(res); //add this...
}
});
}
</script>
}
Partial View(_IndexPartial.cshtml):
#model IEnumerable<SalesOffice_Plant>
<table class="table">
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Employee)
</td>
</tr>
}
</tbody>
</table>
Controller:
[HttpPost]
public ActionResult Index([FromBody] string userCounty)
{
string county = userCounty.Substring(0, userCounty.IndexOf(" "));
var query = from SOP in _context.SalesOffice_Plant
where SOP.County == county
select new SalesOffice_Plant
{
Employee = SOP.Employee
};
return PartialView("_IndexPartial", query.ToList()); //must specify the partial view name
//otherwise it will match the action name as partial view name
}
[HttpGet]
public ActionResult Index()
{
ViewData["Title"] = "Contact Us";
ViewBag.Current = "Contact";
return View();
}
Result:
I'm trying to load a partial view and change it through a POST Ajax, but model doesn't update on view.
This is how I'm loading my partial:
#{
Html.RenderAction("UltimeNovità", "User");
}
and my action in UserController is:
public ActionResult UltimeNovità()
{
_UltimeNovitàViewModel model = new _UltimeNovitàViewModel();
model.NumeroPagina = 1;
return PartialView("~/Views/User/Partial/_UltimeNovità.cshtml",model);
}
and here the partial:
#model Mine.Models._UltimeNovitàViewModel
<script>
$(document).ready(function () {
});
function nextPage() {
$.ajax({
url: '#Url.Action("UltimeNovitàPaginaSuccessiva")',
type: 'POST',
data: { pagina: #Model.NumeroPagina },
success: function (data) {
$('#x').text('#Model.NumeroPagina');
},
error: function (xhr) {
alert('error');
}
});
}
</script>
<p id="x">1</p>
finally, the POST action in the same controller:
[HttpPost]
public ActionResult UltimeNovitàPaginaSuccessiva(int pagina)
{
_UltimeNovitàViewModel model = new _UltimeNovitàViewModel();
ModelState.Clear();
model.NumeroPagina = pagina + 1;
model.UltimeNovità = UserControllerMethods.GetUltimeNovità(model.NumeroPagina);
return PartialView("~/Views/User/Partial/_UltimeNovità.cshtml", model);
}
My problem is: why after the POST action #Model.NumeroPagina is always 1? I expect that each time I press the button which calls the function with ajax the #Model.NumeroPagina increases by 1 and it's shown in my paragraph.
The button is in the main page that contains the partial, actions are always hit and during debugging I can see that model.NumeroPagina is 2, but in view is always 1.
There are some issues in your code. I don't see where you're updating the HTML content, also you're generating the nextPage function eachTime, and others.
Check this sample, it should be easy to use.
Controller/ViewModel
public class NovitàController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult UltimeNovità(int? page)
{
var model = new UltimeNovitàViewModel
{
NumeroPagina = 1
};
return PartialView("_UltimeNovità", model);
}
[HttpPost]
public ActionResult UltimeNovitàPaginaSuccessiva(int pagina)
{
var model = new UltimeNovitàViewModel
{
NumeroPagina = pagina + 1,
UltimeNovità = GetUltimeNovità(pagina + 1)
};
return PartialView("_UltimeNovità", model);
}
public string GetUltimeNovità(int page)
{
return $"Ultime Novità: {page}"; //FOR DEMO
}
public class UltimeNovitàViewModel
{
public int NumeroPagina { get; set; }
public string UltimeNovità { get; set; }
}
}
_UltimeNovità partial view:
#model NovitàController.UltimeNovitàViewModel
#if (Model.UltimeNovità != null)
{
<div>
UltimeNovità: #Model.UltimeNovità
</div>
}
<div>
Pagina: #Model.NumeroPagina
</div>
<div>
<a class="next-page-link" href="#Url.Action("UltimeNovitàPaginaSuccessiva", "Novità", new {pagina = Model.NumeroPagina})">
Pagina Successiva
</a>
</div>
And the Index page:
#{
ViewBag.Title = "Novità";
}
<div id="RootDiv">
#{ Html.RenderAction("UltimeNovità", "Novità");}
</div>
#section scripts{
<script>
$(function() {
function bindNextPageLink() {
$("#RootDiv a.next-page-link").click(function(event) {
event.preventDefault();
$.post($(this).attr("href"),
function(data) {
$("#RootDiv").html(data);
bindNextPageLink();
}
);
});
}
bindNextPageLink();
});
</script>
}
I tried to write the example very similar to your code.
This is my /Books/userHome view:
#model CSBSTest.Models.tbl_Book
#{
ViewBag.Title = "UserHome";
Layout = "~/Views/Shared/_Profile.cshtml";
}
<h2>Books for sale by CUST Students</h2>
<br />
<br />
<table id="books" class="table table-bordered table-hover">
<thead>
<tr>
<th>Id</th>
<th>Book Name</th>
<th>Author</th>
<th>Version</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section scripts
{
<script>
$(document).ready( function () {
var dataTable = $("#books").DataTable({
ajax: {
url: "/Book/GetBooks",
dataSrc: ""
},
columns: [
{
data:"Id"
},
{
data: "Name"
},
{
data: "Author"
},
{
data: "Version"
}
]
});
});
</script>
}
I am calling /Books/GetBooks as below:
public ActionResult UserHome()
{
return View();
}
public ActionResult GetBooks()
{
var list = _context.tbl_Book.ToList();
return Json(list, JsonRequestBehavior.AllowGet);
}
The GetBooks returns json result which is called from UserHome scripts section as shown above, I want to populate the list returned by /Books/GetBooks into jquery datatable but its gives the following exception:
.
any help will be highly appreciated thanks in advance.
var list = _context.tbl_Book.ToList();
Here "list" is database table object and you should not return it directly.
Use user defined model and than return it
public class customModel{
//properties
}
var list = _context.tbl_Book.ToList();
List<custommodel> test = list.select(a=>new custommodel{
//assingn properties
});
return Json(test , JsonRequestBehavior.AllowGet);
I am currently working on an accounting project and I am experiencing a stupid problem.
I enter the values in text boxes and I click on Add Person button, the values get added but when I click Save to Database button the multiple added values get pushed into database. I am able to insert multiple values in the database but unable to call the multiple entries from the SQL server back again onto my UI.
I have multiple same first names in my table of SQL server and I want to pick up all the values which have the same first name and populate them in $scope.arr I defined in angular code.
When I pass an integer value in my $scope.GetPerson() method, I get the desired result and my array ($scope.arr) gets populated with all the values having the same CustomerCode but when I pass a string value i.e, FirstName in GetPerson method, my array($scope.arr) doesn't get populated with the same First Name values that were placed into the database.
I want the experts to look into this problems and guide me where am I actually doing the mistake.`
My Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TestProj.Models
{
public class TestModel
{
public int ID { get; set; }
public int CustomerCode { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Debit { get; set; }
public decimal Credit { get; set; }
}
}
My Angular JS script:
var app = angular.module("TestApp", []);
app.controller("TestCtrl", function ($scope, TestService) {
$scope.arr = [];
GetAllPers();
function GetAllPers() {
var getPersData = TestService.getPersons();
getPersData.then(function (Persons) {
$scope.persons = Persons.data;
}, function () {
alert('Error in getting Person records');
});
}
$scope.addPerson = function () {
var obj = {
CustomerCode: $scope.customercode,
FirstName: $scope.firstname,
LastName: $scope.lastname,
Debit: $scope.debit,
Credit: $scope.credit,
};
$scope.arr.push(obj);
};
$scope.savePerson = function () {
var TestData = TestService.AddPer($scope.arr);
TestData.then(function (msg) {
$scope.customercode = "";
$scope.firstname = "";
$scope.lastname = "";
$scope.debit = "";
$scope.credit = "";
GetAllPers();
alert(msg.data);
for (var i = 0; i < $scope.arr.length; i++) {
$scope.arr.pop();
}
}, function () {
alert('Error In Adding Person');
});
};
$scope.GetPerson = function (test) {
var getTestData = TestService.getPers(test.FirstName);
getTestData.then(function (_test) {
$scope.arr = _test.data;
}, function () {
alert('Error in getting person records');
});
}
});
app.service("TestService", function ($http) {
this.getPersons = function () {
return $http.get("/Test/GetAllPers");
}
this.AddPer = function (person) {
var response = $http({
method: "post",
url: "/Test/AddPerson",
data: JSON.stringify(person),
dataType: "json",
});
console.log(response);
return response;
}
this.getPers = function (persname) {
var response = $http({
method: "post",
url: "/Test/GetPersonByFName",
params: {
firstname: JSON.stringify(persname)
}
});
return response;
}
});
My C# controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestProj.Models;
namespace TestProj.Controllers
{
public class TestController : Controller
{
TestContext dc = new TestContext();
// GET: Test
public ActionResult Index()
{
return View();
}
public JsonResult GetAllPers()
{
var personList = dc.TestModels.ToList();
return Json(personList, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPersonByFName(string firstname)
{
var q = (from ab in dc.TestModels.Where(b => b.FirstName == firstname) select ab);
return Json(q, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public string AddPerson(List<TestModel> test)
{
bool val = false;
foreach (var t in test)
{
if (t != null)
{
dc.TestModels.Add(t);
val = true;
}
else
{
val = false;
}
}
dc.SaveChanges(); //save context at the end, when no error occurs
if (val == true)
{
return "Success";
}
else
{
return "Failed";
}
}
}
}
My HTML:
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div ng-controller="TestCtrl">
<form>
<button class="btn" data-toggle="modal" data-target="#myModal">Show records</button><br />
Customer Code: <input class="form-control" ng-model="customercode" /><br />
FirstName: <input class="form-control" ng-model="firstname" /><br />
LastName: <input class="form-control" ng-model="lastname" /><br />
Debit: <input class="form-control" ng-model="debit" /><br />
Credit: <input class="form-control" ng-model="credit" /><br />
<button class="btn btn-success" ng-click="addPerson()">Add Person</button>
<button class="btn btn-success" ng-click="savePerson()">Save To DB</button>
#*Table for showing pushed values*#
<table class="table table-bordered">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Debit</th>
<th>Credit</th>
</tr>
<tr ng-repeat="a in arr">
<td>{{a.CustomerCode}}</td>
<td>{{a.FirstName}}</td>
<td>{{a.LastName}}</td>
<td>{{a.Debit}}</td>
<td>{{a.Credit}}</td>
</tr>
</table>
#*Modal popup*#
<div class="modal fade" role="dialog" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4>Persons</h4>
</div>
<div class="modal-body">
<label class="control-label col-md-2" style="width: auto">Search:</label>
<div class="col-md-8">
<input class="form-control" ng-model="searchfor" />
</div><br />
<table class="table table-hover">
<tr>
<td><b>First Name</b></td>
<td><b>Last Name</b></td>
<td><b>Debit</b></td>
<td><b>Credit</b></td>
<td><b>Select</b></td>
</tr>
<tr ng-repeat="b in persons | filter:searchfor ">
<td>{{b.CustomerCode}}</td>
<td>{{b.FirstName}}</td>
<td>{{b.LastName}}</td>
<td>{{b.Debit}}</td>
<td>{{b.Credit}}</td>
<td>
<button type="button" class="btn btn-success" ng-click="GetPerson(b)" data-dismiss="modal">Select</button>
</td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal">Okay</button>
</div>
</div>
</div>
</div><br />
</form>
</div>
<script src="~/Scripts/MyAngular/Module.js"></script>
The issue is with your getPers(). Adding JSON.stringfy() adds " to your string.
It should be used like this :
this.getPers = function (persname) {
var response = $http({
method: "post",
url: "/Test/GetPersonByFName",
params: {
firstname: persname
}
});
return response;
}
I want to use the ACE online code editor in my project. How do I use it in ASP.NET MVC?
I'd like to save whatever edits are made with that editor in the database. How do I do that?
Let's assume you have a strong typed model with a property called Editor with the data in it. Now use a normal <div> to load the data:
<div id="editor"><%=Model.Editor %></div>
Now you can create an ace editor in place of the div with javascript:
<script src="src/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
window.onload = function() {
var editor = ace.edit("editor");
};
</script>
Now when you want to save the data, for instance via a form post, use something like this to bind it back to the Editor property of the model:
<%=Html.HiddenFor(m=>m.Editor, new { #id = "hidden_editor" }) %>
<!-- this is jQuery, but you can use any JS framework for this -->
<script>
$("form").submit(function () {
$("#hidden_editor").val(editor.getSession().getValue());
});
</script>
In your controller you can now save the data to the database
[HttpPost]
public ActionResult Index (IndexModel model) {
var data = model.Editor;
// save data in database
}
Here is a solution using most recent technologies (Razor/MVC/Ajax) :
$(document).ready(function() {
$("#btnSave").on("click", function () {
$.ajax({
url: '#Url.Action("YourAction", "YourController")',
type: 'POST',
data: { id: #Model.ID,
html: ace.edit("editor").getValue() },
cache: false,
success: function (response) {
alert("Changes saved.");
}
});
});
});
In Controller :
[AjaxAuthorize]
[HttpPost, ValidateInput(false)]
public ActionResult YourAction(string id, string html)
{
if (id == null || String.IsNullOrEmpty(id))
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
// do you stuff
}
This is how I ended up doing it in Razor Views
#model OfficeGx.Cms.Model.ClassName
<div class="form-group row">
<div class="col-lg-11">
#Html.HiddenFor(x => x.CascadingStylesHdn, new { #id = "hidden_cssEditor" })
#Html.LabelFor(x=>x.CascadingStyles)
<div id="cssEditor">#Model.CascadingStyles</div>
</div>
</div>
<div class="form-group row">
<div class="col-lg-11">
#Html.HiddenFor(x => x.JavaScriptHdn, new { #id = "hidden_jsEditor" })
#Html.LabelFor(x => x.JavaScript)
<div id="jsEditor">#Model.JavaScript</div>
</div>
</div>
<script>
var cssEditor;
var jsEditor;
window.onload = function() {
cssEditor = ace.edit("cssEditor");
cssEditor.getSession().setMode("ace/mode/css");
cssEditor.setTheme("ace/theme/twilight");
jsEditor = ace.edit("jsEditor");
jsEditor.getSession().setMode("ace/mode/javascript");
jsEditor.setTheme("ace/theme/xcode");
};
$("form").submit(function () {
$("#hidden_cssEditor").val(window.cssEditor.getSession().getValue());
$("#hidden_jsEditor").val(window.jsEditor.getSession().getValue());
});
</script>
<style>
#cssEditor, #jsEditor {
position: relative;
height: 400px
}
#Model.CascadingStyles
</style>
In my Controller Add/Edit Method
[HttpPost]
[ValidateInput(false)]
public ActionResult AddEdit(Article article, FormCollection formCollection)
{
article.CompanyId = OperatingUser.CompanyId;
article.CascadingStyles = article.CascadingStylesHdn;
article.JavaScript = article.JavaScriptHdn;