My datatable is not picking the json result - asp.net-core

I am using datatables and my get handler returns a json result but the datatable is not displaying it. What am I missing? Here's my code. I am using Visual Studio 2019 3.1 .net core with razor pages. I am trying to call my datatable in the OnGet handler. I tried the post but that did not work either.
My cust class:
public class Cust
{
public int Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
public string PostalCode { get; set; }
}
_layout.cshtml:
<div class="container">
<main role="main" class="pb-3">
#RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2022 - testApp - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.js"></script>
#RenderSection("Scripts", required: false)
My Index.cshtml.cs model code:
public class IndexModel : PageModel
{
[BindProperty]
public int Draw { get; set; }
// public IEnumerable<Column> Columns { get; set; }
// public IEnumerable<Order> Order { get; set; }
public int Start { get; set; }
public int Length { get; set; }
public List<Cust> Customers = new List<Cust>();
public JsonResult OnGet()
{
var recordsTotal = 3;
Cust cs1 = new Cust();
cs1.Id = 1;
cs1.Name = "test1";
cs1.Address = "address1";
cs1.PhoneNumber = "11111";
cs1.PostalCode = "1111";
Cust cs2 = new Cust();
cs2.Id = 1;
cs2.Name = "test2";
cs2.Address = "address1";
cs2.PhoneNumber = "11111";
cs2.PostalCode = "1111";
Cust cs3 = new Cust();
cs3.Id = 1;
cs3.Name = "test3";
cs3.Address = "address1";
cs3.PhoneNumber = "11111";
cs3.PostalCode = "1111";
Customers.Add(cs1);
Customers.Add(cs2);
Customers.Add(cs3);
var recordsFiltered = Customers.Count();
var data = Customers;
return new JsonResult(new
{
Draw = Draw,
RecordsTotal = recordsTotal,
RecordsFiltered = recordsFiltered,
Data = data
});
}
My Razor page -- Pages/customers/Index.cshtml:
#page
#model testApp.Pages.Customer.IndexModel
#{
}
<h1>Index</h1>
<p>
</p>
<table id="myTable" class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].PhoneNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Address)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].PostalCode)
</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
#section Scripts {
<script>
$(document).ready(function () {
$('#myTable').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
url: "/customers/Index?handler=OnGet",
"type": "GET",
"dataType": "json"
},
"columns": [
{ "data": "id", "autowidth": true },
{ "data": "name", "autowidth": true },
{ "data": "phoneNumber", "autowidth": true },
{ "data": "address", "autowidth": true },
{ "data": "postalCode", "autowidth": true }
],
"order": [[0, "desc"]]
});
});
</script>
}
Here's my json response.
{
"draw": 0,
"recordsTotal": 3,
"recordsFiltered": 3,
"data": [
{
"id": 1,
"name": "test1",
"phoneNumber": "11111",
"address": "address1",
"postalCode": "1111"
},
{
"id": 1,
"name": "test2",
"phoneNumber": "11111",
"address": "address1",
"postalCode": "1111"
},
{
"id": 1,
"name": "test3",
"phoneNumber": "11111",
"address": "address1",
"postalCode": "1111"
}
]
}
I am just testing it with this project to see if I can get the datatable to work. I will be eventually getting the data from the database. Yes, the volume will be big, thousands of rows.

Here is a whole working demo you could follow:
Page(Pages/customers/Index.cshtml)
#page
#model IndexModel
<h1>Index</h1>
<p>
</p>
<table id="myTable" class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].PhoneNumber)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].Address)
</th>
<th>
#Html.DisplayNameFor(model => model.Customers[0].PostalCode)
</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JS in page:
#section Scripts {
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/customers/Index?handler=Json", //change here...
dataType: "json",
success: OnSuccess,
});
});
function OnSuccess(response) {
console.log(response.data)
$('#myTable').DataTable(
{
data: response.data,
columns: [
{ "data": "id" },
{ "data": "name" },
{ "data": "phoneNumber" },
{ "data": "address" },
{ "data": "postalCode" }
],
});
};
</script>
}
PageModel(Pages/customers/Index.cshtml.cs):
public class IndexModel : PageModel
{
[BindProperty]
public int Draw { get; set; }
// public IEnumerable<Column> Columns { get; set; }
// public IEnumerable<Order> Order { get; set; }
public int Start { get; set; }
public int Length { get; set; }
public List<Cust> Customers = new List<Cust>();
public void OnGet() //add this.....
{
}
public JsonResult OnGetJson() //change handler name..
{
var recordsTotal = 3;
Cust cs1 = new Cust();
cs1.Id = 1;
cs1.Name = "test1";
cs1.Address = "address1";
cs1.PhoneNumber = "11111";
cs1.PostalCode = "1111";
Cust cs2 = new Cust();
cs2.Id = 1;
cs2.Name = "test2";
cs2.Address = "address1";
cs2.PhoneNumber = "11111";
cs2.PostalCode = "1111";
Cust cs3 = new Cust();
cs3.Id = 1;
cs3.Name = "test3";
cs3.Address = "address1";
cs3.PhoneNumber = "11111";
cs3.PostalCode = "1111";
Customers.Add(cs1);
Customers.Add(cs2);
Customers.Add(cs3);
var recordsFiltered = Customers.Count();
var data = Customers;
return new JsonResult(new
{
Draw = Draw,
RecordsTotal = recordsTotal,
RecordsFiltered = recordsFiltered,
Data = data
});
}
}
_Layout.cshtml:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>#ViewData["Title"] - RazorPagesProj3_1</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
</head>
<body>
<header>
//....
</header>
<div class="container">
<main role="main" class="pb-3">
#RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
© 2022 - RazorPagesProj3_1 - <a asp-area="" asp-page="/Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.css" />
<script type="text/javascript" src="https://cdn.datatables.net/v/dt/dt-1.12.1/datatables.min.js"></script>
#RenderSection("Scripts", required: false)
</body>
</html>

Related

Loading the datatable with the data from JsonResult method from the controller, makes alignment fails in footer

I am trying to find the total of 'Net Value' and ' Total Value' in datatable as footer and the total value should be shown inside td element with the same alignment of its other data column. If I try to add footer , the total column shows different position from its data column. The footer should be showed the same column of its data. Here is my code in html. Since I am not able to show the original program , I had to make it in presentable format.
I am showing the data by calling JsonResult method from the controller , But after fetching the data from the Json method and showing the result in datatable with vertical scrolling, the footer value is showed bit far from its data column
#model myModel
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.2/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.4/css/buttons.dataTables.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.13.2/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.4/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.4/js/buttons.html5.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
</head>
<body>
<table id="myTable" class="table table-bordered table-striped" style="width:100%;font-size:90%">
<thead>
<tr>
<th>
Item
</th>
<th>
Net Value
</th>
<th>
Total Value
</th>
</tr>
</thead>
<tbody id="body">
<tr>
<td>Item</td>
<td>NetVal</td>
<td>TotVal</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function () {
var report = {};
report.FromDate = "#Model.FromDate";
report.ToDate = "#Model.ToDate";
report.CustomerCode = "#Model.CustomerCode";
var table = $('#myTable').DataTable({
"processing": true,
"ajax": {
"url": "/mySales/SalesData",
"data": report,
"dataSrc": function (json) {
console.log(json);
return JSON.parse(json);
}
},
"columns": [
{ "data": "Item" },
{ "data": "NetVal" },
{ "data": "TotVal" },
],
"columnDefs": [
{
"className": "dt-center", "targets": "_all"
},
{ "width": "10%", "targets": 0 },
{ "width": "5%", "targets": 1 },
{ "width": "5%", "targets": 2 },
],
"pageLength": 40,
scrollY: "500px",
scrollX: true,
paging: true,
footerCallback: function (row, data, start, end, display) {
var api = this.api(), data;
var intVal = function (i) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '') * 1 :
typeof i === 'number' ?
i : 0;
};
var col1 = api
.column(1)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
var col2 = api
.column(2)
.data()
.reduce(function (a, b) {
return intVal(a) + intVal(b);
}, 0);
$(api.column(1).footer()).html(col1);
$(api.column(2).footer()).html(col1);
},
scrollCollapse: true,
dom: 'Bfrtip',
buttons: [
'copyHtml5',
'excelHtml5',
'csvHtml5',
'pdfHtml5'
]
})
})
</script>
// Controller
public JsonResult SalesData(myModel model)
{
DateTime fromDate = new DateTime();
DateTime toDate = new DateTime();
if (report.FromDate != "" && report.ToDate != "" && report.FromDate != null && report.ToDate != null)
{
fromDate = DateTime.ParseExact(report.FromDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
toDate = DateTime.ParseExact(report.ToDate, "dd/MM/yyyy", CultureInfo.InvariantCulture);
}
report.CustomerCode = "001";
var data = _unitOfWork.GetSummary(report.CustomerCode, fromDate, toDate);
String jsonResult = JsonConvert.SerializeObject(data);
return Json(jsonResult);
}

Model not binding in Razor Page .cshtml through datatables.net

I am new to Asp.Net Core Razor Pages and trying to build a sample application with Datatables.net.
I am trying to send data to cshtml page from .cs but can see the data. If I try to view the data in JSon format can see then but datatable is not getting binded with it.
Below is the code for the same.
Installed datatables.net and datatables.net-dt through Nuget Package Manager for Solution
I need the sample data to be showed under the tables with the UI classses binded with datatables.net
CSHTML.CS
namespace Razor_Harshit.Pages
{
public class IndexModel : PageModel
{
List<Employees> _employee = new List<Employees>()
{
new Employees(){ Name="Harshit",
Email="abc#xyz.com",Gender="Male",Mobile="1234567890",City="Bengaluru"},
new Employees(){ Name="Nitin",
Email="abc#xyz.com",Gender="Male",Mobile="1234567890",City="Bengaluru"},
new Employees(){ Name="Narasi",
Email="abc#xyz.com",Gender="Male",Mobile="1234567890",City="Bengaluru"},
new Employees(){ Name="Shivani",
Email="abc#xyz.com",Gender="FeMale",Mobile="1234567890",City="Bengaluru"},
new Employees(){ Name="Vineet",
Email="abc#xyz.com",Gender="Male",Mobile="1234567890",City="Bengaluru"},
new Employees(){ Name="Kaashu",
Email="abc#xyz.com",Gender="Male",Mobile="1234567890",City="Bengaluru"}
};
public void OnGet()
{
}
public IActionResult OnGetDisplay()
{
return new JsonResult(_employee);
//return Page();
}
}
public class Employees
{
public string Name { get; set; }
public string Email { get; set; }
public string Gender { get; set; }
public string Mobile { get; set; }
public string City { get; set; }
}
}
CSHTML
#page
#model Razor_Harshit.Pages.IndexModel
#{
ViewData["Title"] = "Home page";
}
<html>
<head>
<link rel="stylesheet" type="text/css"
href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
<script type="text/javascript" src="/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" charset="utf8"
src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function () {
debugger;
$('#table1').dataTable({
pageLength: 2,
ajax: "?handler=Display", ,
columns: [
{ data: 'Name' },
{ data: 'Email'},
{ data: 'Gender' },
{ data: 'Mobile' },
{ data:'City' }
]
});
});
</script>
</head>
<body>
<div>
</div>
<div>
<table id="table1" class="display" width="100%">
<tr>
<th>Name</th>
<th>Email</th>
<th>Gender</th>
<th>Mobile</th>
<th>City</th>
</tr>
</table>
</div>
</body>
</html>
Results :
enter image description here
enter image description here
Please modify your code like this:
<html>
<head>
<script type="text/javascript" src="/lib/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.12.1/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function () {
debugger;
$.noConflict();
$('#table1').dataTable({
pageLength: 2,
ajax: {url: "?handler=Display",dataSrc:""},
columns: [
{ data: 'name' },
{ data: 'email'},
{ data: 'gender' },
{ data: 'mobile' },
{ data:'city' }
]
});
});
</script>
</head>
<body>
<div>
</div>
<div>
<table id="table1" class="display" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Gender</th>
<th>Mobile</th>
<th>City</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</body>
</html>
You need to pay attention to the following points:
First,The passed parameter name will be changed to all lowercase by default.
Second,The reference to the jquery library should be before datatables.
Third,If you get this error: "TypeError: $(...).DataTable is not a function", you can call $.noConflict().
Fourth,Change the ajax attribute to match the parameter type.
Fifth,You need to add the <tbody> tag, otherwise the header row will be replaced.
Test Result:

Asp.net core Razor Page - JQ data table not load data

I have an Asp.net core project with Razor Page ,I try to implement a JQ data table but the data not load.
Here is the Javascript code:
$('#dataList').DataTable({
// "iDisplayLength": 100,
// "sPaginationType": "full_numbers",
processing: true,
serverSide: true,
ajax: {
async: true,
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/CoursesDP/?handler=Data',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: function (d) {
// note: d is created by datatable, the structure of d is the same with DataTableParameters model above
// console.log(JSON.stringify(d));
return JSON.stringify(d);
},
success: function (r) {
console.log(r);
}
},
})
I write the data is coming to console:
{"draw":1,"recordsTotal":11,"recordsFiltered":11,"data":[["oooo"],["ccc"],["aaa"],["pppp"],["pppp"],["yyy"],["12"],["pppp"],["pppp"],["pppp"],["fff"]]}
This is the html code:
<table id="dataList" class="display" style="width:100%">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.CourseDP[0].CourseName)
</th>
</tr>
</thead>
but the data not load to the data table .
What can I do?
The following is a working sample using DataTables with testing data, you can refer to it.
CoursesDP.cshtml:
#page
#model ModelValidation_MVC_.Pages.CourseDB.CoursesDPModel
#{
ViewData["Title"] = "CoursesDP";
}
<h1>CourseDP</h1>
<div>
<table id="dataList" class="table table-striped table-bordered" style="width:100%">
<thead class="thead-dark">
<tr class="table-info">
<th>id</th>
<th>name</th>
<th>age</th>
<th>phone</th>
<th>email</th>
</tr>
</thead>
</table>
</div>
#section scripts{
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script type="text/javascript">
$('#dataList').DataTable({
"processing": true,
"serverSide": true,
ajax: {
type: "POST",
url: '/CourseDB/CoursesDP/?handler=Data',
},
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'age' },
{ data: 'phone' },
{ data: 'email' }
]
})
</script>
}
CoursesDP.cshtml.cs:
[IgnoreAntiforgeryToken]
public class CoursesDPModel : PageModel
{
public static List<TestDT> testDTs = new List<TestDT> { new TestDT {id=1, name = "TestDT1", age = 1, phone = "1", email = "TestDT1#.com" },
new TestDT {id=2, name = "TestDT2", age = 2, phone = "2", email = "TestDT2#.com" }, new TestDT {id=3, name = "TestDT3", age = 3, phone = "3", email = "TestDT3#.com" } ,
new TestDT {id=4, name = "TestDT4", age = 4, phone = "4", email = "TestDT4#.com" }, new TestDT {id=5, name = "TestDT5", age = 5, phone = "5", email = "TestDT5#.com" } ,
new TestDT {id=6, name = "TestDT6", age = 6, phone = "6", email = "TestDT6#.com" },new TestDT {id=7, name = "TestDT7", age = 7, phone = "7", email = "TestDT7#.com" },};
public static List<TestId> testIds = new List<TestId> { new TestId { id = 1 }, new TestId { id = 2 } };
public IActionResult OnGet()
{
return Page();
}
public JsonResult OnPostData()
{
Postdata postdata = new Postdata { draw = 1, recordsTotal =7, recordsFiltered = 7, data = testDTs };
return new JsonResult(postdata);
}
}
result:

partial view not displaying on main view post back

In the main view I am calling a partial view. It work fine for normal usage. On the postback the partial view controller bit is never triggered and the partial view does not displayed. What options are available to make sure that the partial view is rendered even when a postback is triggered.
Model:
public class ReportSummary
{
public int PayrollNumber { get; set; }
public string Name { get; set; }
public string ConflictInterest { get; set; }
public string SummaryConflictInterest { get; set; }
public string FinancialInterest { get; set; }
public string SummaryFinancialInterest { get; set; }
public string GiftInterest { get; set; }
public string SummaryGiftInterest { get; set; }
public string Combined { get; set; }
public string SummaryCombined { get; set; }
}
Controller:
Main:
public ActionResult CoiReporting()
{
...
var model = new ReportParamters();
model.Year = DateTime.Today.Year-1;
model.SelectedTab = "0";
...
return View(model);
}
[HttpPost]
[ActionName("CoiReporting")]
public ActionResult CoiReportingConfrim(string ViewReport, ReportParamters model )
{
...
switch (model.SelectedTab)
{
...
}
return View(model);
}
Partial:
public ActionResult _ReportCriteria(int Year=0, int ReportType=0, int Person=0, int Group=0, int Division=0, int Department=0, int Section=0, string SelectedTab="X")
{
...
var model = new ReportParamters();
model.Year = Year;
model.ReportType = ReportType;
model.Person = Person;
model.Group = Group;
model.Division = Division;
model.Department = Department;
model.Section = Section;
model.SelectedTab = SelectedTab;
return PartialView(model);
}
Views:
Main
#model ConflictOfInterest.Models.ReportParamters
#using (Html.BeginForm("CoiReporting", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.HiddenFor(model => model.SelectedTab)
#Html.HiddenFor(model => model.Year)
<div id="tabs">
<ul>
<li>Summary</li>
<li>Statistics</li>
<li>Statistics with Person Detail</li>
</ul>
<div id="tabs-1">
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Show the detail captered by direct reports.</td>
</tr>
</table>
</div>
<div id="tabs-2">
</div>
<div id="tabs-3">
</div>
</div>
<input type="submit" name="ViewReport" id="ViewReport" value="View Report" class="SaveForm" />
<script type="text/javascript">
$(function () {
var sPath = "";
var sParam = "";
$("#tabs").tabs({
activate: function (event, ui) {
var selectedTab = $('#tabs').tabs('option', 'active');
$("#SelectedTab").val(selectedTab);
console.log("Tab selected: " + selectedTab);
var sUrl = "#Url.Action("_ReportCriteria", Model)";
....
$('.ui-tabs-panel').empty();
sParam = aParam.join("&")
ui.newPanel.load(sPath + sParam);
},
active: $("#SelectedTab").val()
});
});
$('#tabs').click('tabsselect', function (event, ui) {
var selectedTab = $("#tabs").tabs("option", "active");
$("#SelectedTab").val(selectedTab);
});
</script>
}
Partial:
#model ConflictOfInterest.Models.ReportParamters
#{
if (Model.SelectedTab != "0")
{
<table border="0" cellpadding="0" cellspacing="0">
#{
if (Model.SelectedTab == "1")
{
<tr>
<td style="font-weight:bolder">#Html.Label("Year", "Year:")</td>
<td>#Html.DropDownListFor(model => model.Year, Enumerable.Empty<SelectListItem>(), (DateTime.Today.Year - 1).ToString(), new { #style = "width:200px;" })
</td>
<td style="font-weight:bolder">#Html.Label("ReportType", "Report Type:")</td>
<td>#Html.DropDownListFor(model => model.ReportType, new SelectList(ViewBag.ReportType, "value", "Text"), new { #style = "width:200px;" })</td>
<td style="font-weight:bolder">
#Html.Label("Person", "Person:")
#Html.Label("Group", "Group:")
</td>
<td>
#Html.DropDownListFor(model => model.Group, new SelectList(ViewBag.GroupList, "value", "Text"), new { #style = "width:200px;" })
#Html.DropDownListFor(model => model.Person, Enumerable.Empty<SelectListItem>(), "All", new { #style = "width:200px;" })<br />
#Html.TextBox("sPerson")
<input type="button" id="bPerson" value="Search" />
</td>
</tr>
}
/*else
{
<tr>
<td colspan="6"></td>
</tr>
}*/
}
<tr>
<td style="font-weight:bolder">#Html.Label("Division", "Division:")</td>
<td>#Html.DropDownListFor(model => model.Division, new SelectList(ViewBag.Division, "value", "Text"), new { #style = "width:200px;" })</td>
<td style="font-weight:bolder">#Html.Label("Department", "Department:")</td>
<td>#Html.DropDownListFor(model => model.Department, Enumerable.Empty<SelectListItem>(), "All", new { #style = "width:200px;" })</td>
<td style="font-weight:bolder">#Html.Label("Section", "Section:")</td>
<td>#Html.DropDownListFor(model => model.Section, Enumerable.Empty<SelectListItem>(), "All", new { #style = "width:200px;" })</td>
</tr>
<tr>
<td colspan="6"></td>
</tr>
</table>
}
else
{
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td>Show the detail captered by direct reports.</td>
</tr>
</table>
}
}
The activate event of the jquery tab is triggered when a tab is activated(selected).
To ensure that the the same action is taking place on post back you need to use the create event as well.
Take note of the difference in the load at the end
create: function (event, ui) {
//event.preventDefault();
var selectedTab = $('#tabs').tabs('option', 'active');
$("#SelectedTab").val(selectedTab);
console.log("Tab selected: " + selectedTab);
var sUrl = "#Url.Action("_ReportCriteria", Model)";
//console.log("Start Url: " + sUrl);
sPath = sUrl.substring(0, sUrl.lastIndexOf("?") + 1);
//console.log("Path: "+sPath);
//console.log("Parameters:"+sUrl.substring(sUrl.lastIndexOf("?") + 1, sUrl.length));
sParam = sUrl.substring(sUrl.lastIndexOf("?") + 1, sUrl.length)
var aParam = sParam.split("&");
for (var i = 0; i < aParam.length; i++) {
var aParama = aParam[i].split("=");
switch (i) {
case 7:
aParama[1] = selectedTab;
break;
}
aParam[i] = aParama.join("=");
}
$('.ui-tabs-panel').empty();
sParam = aParam.join("&")
ui.panel.load(sPath + sParam);
},

Asp .net MVC...HttpPostedFileBase uploadImage is not always null

I want upload an Image but it always gets null. I'm using HttpPostedFileBase.
This is my COntroller
public ActionResult EmployeeDetail(EmployeeModel employee, HttpPostedFileBase UploadImage)//this UploadImage Object is always null
{
EmployeeModel employeeModel = new EmployeeModel();
if (string.IsNullOrEmpty(employeeModel.Name))
{
ModelState.AddModelError("Name", "Name is Required");
}
employeeModel.Name = employee.Name;
if (string.IsNullOrEmpty(employeeModel.DOJ))
{
ModelState.AddModelError("DOJ", "DOJ is Requird");
}
employeeModel.DOJ = employee.DOJ;
if (string.IsNullOrEmpty(employeeModel.DOB))
{
ModelState.AddModelError("DOB", "DOB is Required");
}
employeeModel.DOB = employee.DOB;
if (string.IsNullOrEmpty(employeeModel.Designation))
{
ModelState.AddModelError("Designation", "Designation is required");
}
employeeModel.Designation = employee.Designation;
string ImageName = Path.GetFileName(UploadImage.FileName);
string Physicalpath = Server.MapPath("~/images/" + ImageName);
UploadImage.SaveAs(Physicalpath);
employee.UploadImage = Physicalpath;
//string ImageName = Path.GetFileName(image.FileName);
//string physicalPath = Server.MapPath("~/images/" + ImageName);
//image.SaveAs(physicalPath);
// ModelState.AddModelError("UploadImage", "upload is required");
//employee.UploadImage = physicalPath;
EmployeeBusinessLayer employeeBL = new EmployeeBusinessLayer();
employeeBL.InsertDataRegistration(employeeModel);
return RedirectToAction("Index");
}
This is my View
#using (Html.BeginForm("EmployeeDetail", "Home", FormMethod.Post, new { enctype = "multipart/form-data", #data_ajax = "false" })) //i have used all the codes which could be need to make it work...still not working
{
<div class="MainDiv">
<table class="Table">
<tr class="Row">
<td class="Column1"> Name</td>
<td class="Column2">#Html.TextBoxFor(model => model.Name) #Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr class="Row">
<td class="Column1">DOJ </td>
<td class="Column2">#Html.TextBoxFor(model => model.DOJ, new { #class = "datepicker", autocomplete = "off" }) #Html.ValidationMessageFor(model => model.Name) </td>
</tr>
<tr class="Row">
<td class="Column1">DOB</td>
<td class="Column2">#Html.TextBoxFor(model => model.DOB, new { #class = "datepicker", autocomplete = "off" }) #Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr class="Row">
<td class="Column1">DESIGNATION</td>
<td class="Column2">#Html.TextBoxFor(model => model.Designation) #Html.ValidationMessageFor(model => model.Name)</td>
</tr>
<tr class="Row">
<td class="Column1">UPlOAD </td>
<td class="Column2">#Html.TextBoxFor(model => model.UploadImage, new { #type = "File" })
</td>
</tr>
<tr class="Row">
<td colspan="2">
<input type="submit" class="button" name="submit" value="Submit">
<input type="reset" class="button1" value="Clear" name="Clear">
</td>
</tr>
</table>
<script src="~/Scripts/jquery-ui-1.9.2.custom/development-bundle/jquery-1.8.3.js"></script>
<script src="~/Scripts/jquery-ui-1.9.2.custom/development-bundle/ui/minified/jquery-ui.custom.min.js"></script>
<script type="text/javascript">
$(function () {
// This will make every element with the class "date-picker" into a DatePicker element
$('.datepicker').datepicker();
})
</script>
</div>
}
this is my Model
public Model
{
public int EmployeeId { get; set; }
[Required(ErrorMessage = "this is required")]
public string Name { get; set; }
[Required (ErrorMessage = "This is required")]
public string DOJ { get; set; }
[Required(ErrorMessage ="This is required")]
public string DOB { get; set; }
[Required(ErrorMessage ="This is required")]
public string Designation { get; set; }
[Required(ErrorMessage = "This is required")]
public string UploadImage { get; set; }
public HttpPostedFileBase MyFile { get; set; }
}
I don't see anywhere you are passing any parameter to EmployeeDetail(). Are you able to get data for your EmployeeModel? If yes, then that at least confirm that your view able to call the EmployeeDetail() action.
Next, you need to make sure you are passing proper parameter to your EmployeeDetail(). One of the way I could think of is to use ajax. So you can create an ajax call when submit button is clicked, and pass all your data and the uploaded file input in the ajax method.
This is an example of using ajax call with JQuery syntax to pass data to the action
var inputFiles = $('inpFile').val();
var actMethod = "#Url.Action("EmployeeDetail", "Index")"
var postData = {
"Name": $('inpName').val(),
"DOJ": $('inpDOJ').val(),
...
"UploadImage": inputFiles
}
$.ajax()
{
url: actMethod ,
data: postData,
type: "POST",
success: function (data) {
alert("Insert Successful!");
}
}