The Linq Query Returns Errors - c#

I am consuming wcf rest service into angular js application . I am joining three tables records into a single record and displaying it in web application . I want when i click the button with account number it should returns user account information like account number , Money In ,Money Out ,Date and Account Balance etc . But i got following errors in google chrome network tab ..
The server encountered an error processing the request. The exception message is 'The type 'HalifaxWCFProject.Transcation.AccountTransaction' appears in two structurally incompatible initializations within a single LINQ to Entities query. A type can be initialized in two places in the same query, but only if the same properties are set in both places and those properties are set in the same order.'. See server logs for more details. The exception stack trace is:
Here is the Class .
public class AccountTransaction
{
public int? Account_Number { get; set; }
public decimal? Deposit { get; set; }
public decimal? Withdrawal { get; set; }
public decimal? Account_Balance { get; set; }
public string Date { get; set; }
}
Here is the Linq Query .
public string TranscationDetails(string Account_Number)
{
var accountNumber = int.Parse(Account_Number);//It could be better to use TryParse
using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
{
var inOut = context.Current_Account_Deposit.Where(x => x.Account_Number == accountNumber).Select(w => new AccountTransaction
{
Account_Number = w.Account_Number,
Deposit = (decimal?)null,
Withdrawal = (decimal?)w.Amount,
Date = w.Date
}).Concat(context.Current_Account_Withdraw.Where(x => x.Account_Number == accountNumber).Select(d => new AccountTransaction
{
Account_Number = d.Account_Number,
Deposit = (decimal?)d.Amount,
Withdrawal = (decimal?)null,
Date = d.Date
})).OrderBy(r => r.Date)
.Concat(context.Current_Account_Details.Where(x => x.Account_Number == accountNumber).Select(e => new AccountTransaction
{
Account_Number = e.Account_Number,
Account_Balance = (decimal?)e.Account_Balance
}));
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
return js.Serialize(inOut); // return JSON string
}
}
}
}
Here is my angular js code .
#{
Layout = null;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
$scope.IsVisible = false;
$scope.Search = function () {
var post = $http({
method: "GET",
url: "http://localhost:52098/HalifaxIISService.svc/TranscationDetails/" + encodeURIComponent($scope.Account_Number),
dataType: 'json',
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/json; charset=utf-8'
}
});
post.then(function (response) { // .success(function(data => .then(function(response
var data = response.data; // extract data from resposne
$scope.Customers = JSON.parse(data); // eval(data.d) => JSON.parse(data)
$scope.IsVisible = true;
}, function (err) {
$window.alert(err);
});
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
Account Number:
<input type="text" ng-model="Account_Number" />
<input type="button" value="Submit" ng-click="Search()" />
<hr />
<table style="border: solid 2px Green; padding: 5px;" ng-show="IsVisible">
#*<table cellpadding="0" cellspacing="0">*#
<tr style="height: 30px; background-color: skyblue; color: maroon;">
<th></th>
<th> Account Number</th>
<th> Money In</th>
<th>Date</th>
<th> Money Out</th>
<th>Date</th>
<th>Account Balance</th>
<th></th>
<th></th>
</tr>
<tbody ng-repeat="m in Customers">
<tr style="height: 30px; background-color: skyblue; color: maroon;">
<td></td>
<td><span>{{m.Account_Number}}</span></td>
<td><span>{{m.Deposit| currency:"£"}}</span></td>
<td><span>{{m.Date}}</span></td>
<td><span>{{m.Withdrawal | currency:"£"}}</span></td>
<td><span>{{m.Date}}</span></td>
<td><span>{{m.Account_Balance| currency:"£"}}</span></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Here is the database
Here is the Model.
Here is the Screen Shot On Debugging mode ..
Here is the result when i run the application

Try below code, Added all the properties of AccountTransaction add use Union instead Concat
Union will return distinct values but here your comparison is with reference of your items thus all items will be considered as different. Concat is equivalent to Union All
public string TranscationDetails(string Account_Number)
{
var accountNumber = int.Parse(Account_Number);//It could be better to use TryParse
using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
{
var inOut = context.Current_Account_Deposit.Where(x => x.Account_Number == accountNumber).Select(w => new AccountTransaction
{
Account_Number = w.Account_Number,
Account_Balance = (decimal?)0M,
Deposit = (decimal?)null,
Withdrawal = (decimal?)w.Amount,
Date = w.Date
}).Union(context.Current_Account_Withdraw.Where(x => x.Account_Number == accountNumber).Select(d => new AccountTransaction
{
Account_Number = d.Account_Number,
Account_Balance = (decimal?)0M,
Deposit = (decimal?)d.Amount,
Withdrawal = (decimal?)null,
Date = d.Date
})).OrderBy(r => r.Date)
.Union(context.Current_Account_Details.Where(x => x.Account_Number == accountNumber).Select(e => new AccountTransaction
{
Account_Number = e.Account_Number,
Account_Balance = (decimal?)e.Account_Balance,
Deposit = (decimal?)0M,
Withdrawal = (decimal?)0M,
Date = DateTime.Now
}));
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
return js.Serialize(inOut); // return JSON string
}
}
}
}

Related

Ajax & ASP.NET Core MVC 6..0 : Get data by ID without using Entity Framework

I am trying to get data in my DataTable by ID, the data row coming from SQL Server to my controller and passing to Jquery-Ajax but After processing in Ajax, I am getting only UNDEFINED in my DataTable View?
Please note: I have used below code successfully in my ASP.Net MVC app but now after upgrading to ASP.NET CORE MVC 6.0, It is giving only UNDEFINED.
my model:
public class EmployeesModel
{
public int EmployeeId { get; set; }
public string? Name { get; set; }
public string? Gender { get; set; }
public int Age { get; set; }
public string? Position { get; set; }
public string? Office { get; set; }
[Required(ErrorMessage = "Please enter date")]
public DateTime HiringDate { get; set; }
public int Salary { get; set; }
}
My controller
[HttpGet]
public JsonResult GetEmpByName(string Name)
{
List<EmployeesModel> employeeList = new List<EmployeesModel>();
string CS = this.Configuration.GetConnectionString("SQLConn");
using (SqlConnection conn = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SP_GetEmpByName", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#EmpName", SqlDbType.NVarChar).Value = Name; //Added Parameter
conn.Open();
// Get
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
EmployeesModel employee = new EmployeesModel();
employee.EmployeeId = Convert.ToInt32(reader["EmployeeId"]);
employee.Name = reader["Name"].ToString();
employee.Gender = reader["Gender"].ToString();
employee.Age = Convert.ToInt32(reader["Age"]);
employee.Position = reader["Position"].ToString();
employee.Office = reader["Office"].ToString();
employee.HiringDate = Convert.ToDateTime(reader["HiringDate"]);
employee.Salary = Convert.ToInt32(reader["Salary"]);
employeeList.Add(employee);
}
}
return Json(new { data = employeeList.ToList(), success = true, responsetext = "Added" });
}
My view
#model IEnumerable<SQLWithoutEF.EmployeesModel>
<div class="form-control">
<select class="form-select" id="drpList" onchange="getSelectedValue()">
<option selected disabled>Please Select</option>
#foreach(var employee in ViewBag.Employees)
{
<option value="#employee.EmployeeId">#employee.Name</option>
}
</select>
</div>
//Here I enter Employee Name and below is button
<Button runat="server" Text="Button" class="btn btn-danger" id="IDbtn" onclick="GetByName($('#drpList').val())">Get Data By Name</Button>
#*Data Table ==============*#
<table class="table table-bordered table-responsive table-hover" id="MyTable">
<thead>
<tr>
<th style="display:none">#Html.DisplayNameFor(m => m.EmployeeId)</th>
<th>#Html.DisplayNameFor(m => m.Name)</th>
<th>#Html.DisplayNameFor(m => m.Gender)</th>
<th>#Html.DisplayNameFor(m => m.Age)</th>
<th>#Html.DisplayNameFor(m => m.Position)</th>
<th>#Html.DisplayNameFor(m => m.Office)</th>
<th>#Html.DisplayNameFor(m => m.HiringDate)</th>
<th>#Html.DisplayNameFor(m => m.Salary)</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var employee1 in Model)
{
<tr>
<td style="display:none">#employee1.EmployeeId</td>
<td>#employee1.Name</td>
<td>#employee1.Gender</td>
<td>#employee1.Age</td>
<td>#employee1.Position</td>
<td>#employee1.Office</td>
<td>#employee1.HiringDate</td>
<td>#employee1.Salary</td>
<td>
<asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> |
<asp:button class="btn btn-danger btn-xs" data-name="#employee1.Name" id="deletebtn" onclick="deleteF(#employee1.EmployeeId)">DeleteEmp</asp:button>
</td>
</tr>
}
</tbody>
</table>
My jQuery / Ajax - here I need help: I have tried 3 methods but all fail
function GetByName(Name) {
$('#MyTable tbody tr').remove();
$.ajax({
type: "GET",
url: '/Home/GetEmpByName?Name=' + Name,
//data: JSON.stringify({ id: id }), commented out
//contentType: application/json, charset: utf - 8, commented out
//cache: false, commented out
processData: false,
dataType: 'json',
bprocessing: true,
success: function (data) {
var items = [data.data[0]]; //This line may be wrong, I am not sure.
debugger;
3rd try -Failed
//let rows = data.map(i=> "<tr><td>" + i.Name + "</td></tr>");
2nd try -failed
// for (var i = 1; i < items.length-1; i++) {
// var rows = $('<tr> <td style="Display:none">' + items[EmployeeID] + '</td><td>' + items.data[i].Name + '</td><td>' + items[i][2] + '</td><td>' + items[i][3] + '</td><td>' + items[i][4] + '</td><td>' + items[i][5] + '</td><td>' + items[i][6] + '</td><td>' + items[i][7] + '</td><td>' + items[i][8] + '</td></tr>');
// $('#MyTable tbody').append(rows);
// };
// 1st try failed
$.each(items, function (index, item) {
var rows = '';
rows = `<tr>
<td style="Display:none">${item.EmployeeId}</td>
<td>${item.Name}</td>
<td>${item.Gender}</td>
<td>${item.Age}</td>
<td>${item.Position}</td>
<td>${item.Office}</td>
<td>${2020-04-04}</td>
<td>${item.Salary}</td>
<td><asp:button class="btn btn-info btn-xs updbtn1">UpdateEmp</asp:button> | <asp:button class="btn btn-danger btn-xs" data-name="${item.Name}" id="deletebtn" onclick="deleteF(${item.EmployeeId})">DeleteEmp</asp:button></td>
</tr>`
$('#MyTable tbody').append(rows);
});
},
complete: function () {
// setTimeout(function () {
// $('.ajaxLoader').hide();
// }, 300);
}
}).catch(function (xhr, status, error) {
var errorMeassage = xhr.status + ': ' + xhr.statusText;
alert('Error - ' + errorMeassage);
})
};
};
Here is the screenshot what output I am getting
How can I send data from my controller to my DataTable using Ajax?
It's because you return your data with employeeId, name properties but you try to append with EmployeeId, Name. You need to be careful with casing of your object.
rows = `<tr>
<td style="Display:none">${item.employeeId}</td>
<td>${item.name}</td>
<td>${item.gender}</td> ...

Server side paging & sorting and filtering Performance

I have only one table in database with 2 million records , i want the user to be able to browse the data and also have the ability to sort data and filter it.
also user should be able to navigate between pages
Here is my MVC controller
public class AssetController : Controller
{
private ApplicationDbContext _dbContext;
public ApplicationDbContext DbContext
{
get
{
return _dbContext ?? HttpContext.GetOwinContext().Get<ApplicationDbContext>();
}
private set
{
_dbContext = value;
}
}
public AssetController()
{
}
public AssetController(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
// GET: Asset
public ActionResult Index()
{
return View();
}
public ActionResult Get([ModelBinder(typeof(DataTablesBinder))] IDataTablesRequest requestModel)
{
IEnumerable<Asset> query = DbContext.Assets;
var totalCount = query.Count();
#region Filtering
// Apply filters for searching
if (requestModel.Search.Value != string.Empty)
{
var value = requestModel.Search.Value.Trim();
query = query.Where(p => p.Barcode.Contains(value) ||
p.Manufacturer.Contains(value) ||
p.ModelNumber.Contains(value) ||
p.Building.Contains(value)
);
}
var filteredCount = query.Count();
#endregion Filtering
#region Sorting
// Sorting
var sortedColumns = requestModel.Columns.GetSortedColumns();
var orderByString = String.Empty;
foreach (var column in sortedColumns)
{
orderByString += orderByString != String.Empty ? "," : "";
orderByString += (column.Data) + (column.SortDirection == Column.OrderDirection.Ascendant ? " asc" : " desc");
}
query = query.OrderBy(orderByString == string.Empty ? "BarCode asc" : orderByString);
#endregion Sorting
// Paging
query = query.Skip(requestModel.Start).Take(requestModel.Length);
var data = query.Select(asset => new
{
AssetID = asset.AssetID,
BarCode = asset.Barcode,
Manufacturer = asset.Manufacturer,
ModelNumber = asset.ModelNumber,
Building = asset.Building,
RoomNo = asset.RoomNo,
Quantity = asset.Quantity
}).ToList();
return Json(new DataTablesResponse(requestModel.Draw, data, filteredCount, totalCount), JsonRequestBehavior.AllowGet);
}
}
and below is index.cshtml
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary list-panel" id="list-panel">
<div class="panel-heading list-panel-heading">
<h1 class="panel-title list-panel-title">Properties</h1>
</div>
<div class="panel-body">
<table id="datatable" class="table table-striped table-bordered" style="width:100%;">
<thead>
<tr>
<th>BarCode</th>
<th>Manufacturer</th>
<th>Building</th>
<th>Quantity</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
#section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
var datatableInstance = $('#datatable').DataTable({
serverSide: true,
processing: true,
"ajax": {
"url": "#Url.Action("Get","Asset")"
},
lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
columns: [
{ 'data': 'BarCode' },
{ 'data': 'Manufacturer' },
{
'data': 'Building',
'searchable': true,
},
{
'data': 'Quantity',
'searchable': true,
'render': function (Quantity) {
return "$ " + Quantity;
}
},
],
});
});
</script>
}
I used JQuery data-tables , code is working fine if i have small number of rows - less than 100000 , but if i have large number of rows , it becomes very bad
It takes too long in the following line
var filteredCount = query.Count();
How can i enhance the performance
In my opinion, instead doing "var totalCount = query.Count();" try to make an sql statement with a count over the table, probably you will get a better perfomance.
var totalCount = _context.SqlQuery("Select count(0) from yourTable").FirstOrDefault();
I haven´t tested the perfomance with Count(), but with Distinc() the difference is remarkable.
Hope it helps

not refreshing data in angular js

I write a web in mvc framework with angular js.
my application is:
var app = angular.module("AngularApp", []);
and my controller is:
app.controller("EmpCtrl", function ($scope, EmployeeService) {
GetAllEmployee();
function GetAllEmployee() {
var getAllEmployee = EmployeeService.getEmployee();
getAllEmployee.then(function (emp) {
$scope.employees = emp.data;
}, function () {
alert('data not found');
});
}
$scope.deleteEmployee = function (id) {
var getData = EmployeeService.DeleteEmp(id);
getData.then(function (msg) {
GetAllEmployee();
alert('Employee Deleted...');
$scope.h1message = true;
$scope.message = "ED";
}, function () {
$scope.h1message = true;
$scope.message = "Error in Deleting Record";
});
}
});
and my service is:
app.service("EmployeeService", function ($http) {
this.getEmployee = function () {
debugger;
return $http.get("/EmployeeModels/GetAllEmployee");
};
//Delete Employee
this.DeleteEmp = function (employeeId) {
var response = $http({
method: "post",
url: "/EmployeeModels/deleteEmployee",
params: {
employeeId: JSON.stringify(employeeId)
}
});
return response;
}
});
and my mvc action is :
private ApplicationDbContext db = new ApplicationDbContext();
public JsonResult GetAllEmployee()
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
var employeeList = db.EmployeeModels.ToList();
return Json(employeeList, JsonRequestBehavior.AllowGet);
}
}
//DeleteEmployee
public string DeleteEmployee(string employeeId)
{
if (employeeId != null)
{
int no = Convert.ToInt32(employeeId);
var employeeList = db.EmployeeModels.Find(no);
db.EmployeeModels.Remove(employeeList);
db.SaveChanges();
return "Employee Deleted";
}
else { return "Invalid Employee"; }
}
and html file is:
<div ng-app="AngularApp" ng-init="name='hn';backGroundColor='red';
person={firstname:'jo',lastname:'hary'}">
<div ng-controller="EmpCtrl">
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('emp.EmployeeId')">employee id</th>
<th ng-click="orderByMe('Address')">addres</th>
<th ng-click="orderByMe('EmailId')">email id</th>
<th ng-click="orderByMe('EmployeeName')">employee name</th>
</tr>
<tr ng-repeat="emp in employees|orderBy:orderByMe">
<td> {{emp.EmployeeId}}</td>
<td> {{emp.Address}}</td>
<td>{{emp.EmailId}}</td>
<td>{{emp.EmployeeName}}</td>
<td><a data-ng-click="deleteEmployee(emp.EmployeeId)" style="cursor:pointer;">delete</a></td>
</tr>
</table>
</div>
the view of data is ok. but when I add record to table of database, view not refresh data?
Your view not refresh data because, your method GetAllEmployee() is called once, at the loading of page. you need to refresh your page.

better way to load 2 dropdown in mvc

This is how i am loading on page load state and city dropdown:
My Controller method:
This is the first method which is calling when page is loaded.
public ActionResult Index()
{
var states = GetStates();
var cities = Enumerable.Empty<SelectListItem>();
ViewBag.States = states;
ViewBag.Cities = cities;
}
private IEnumerable<SelectListItem> GetStates()
{
using (var db = new DataEntities())
{
return db.States.Select(d => new SelectListItem { Text = d.StateName, Value =d.Id.ToString() });
}
}
[HttpGet]
public ActionResult GetCities(int id)
{
using (var db = new DataEntities())
{
var data = db.Cities.Where(d=>d.StateId==id).Select(d => new { Text = d.CityName, Value = d.Id }).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
My View:
IEnumerable<SelectListItem> States = ViewBag.States;
IEnumerable<SelectListItem> Cities = ViewBag.Cities;
#Html.DropDownList("State", States, "Select State", new { onchange="loadCities(this)"})
#Html.DropDownListFor(m => m.CityId, Cities, "Select City", new { id="ddlCity"})
function loadCities(obj) {
$.ajax({
url: "/Home/GetCities",
data: { id: $(obj).val() },
contentType:"application/json",
success:function(responce){
var html = '<option value="0">Select City</option>';
$(responce).each(function () {
html += '<option value="'+this.Value+'">'+this.Text+'</option>'
});
$("#ddlCity").html(html);
}
});
}
Any better way then this to load state and city dropdown?
public class HomeController : Controller
{
public ActionResult Index(int id=0)
{
Person model = null;
var states = GetStates().ToList();
var cities = Enumerable.Empty<SelectListItem>();
if (id > 0)
{
using (var db = new DataEntities())
{
model = db.People.Include("City").FirstOrDefault(d => d.Id == id);
if (model == null)
model = new Person();
else
{
states.First(d => d.Value == model.City.StateId.ToString()).Selected = true;
cities = db.Cities.Where(d => d.StateId == model.City.StateId).ToList().Select(d => new SelectListItem { Text = d.CityName,Value=d.Id.ToString(),Selected=d.Id==model.CityId });
}
}
}
else
{
model = new Person();
}
ViewBag.States = states;
ViewBag.Cities = cities;
ViewBag.Persons = GetPersons();
return View(model);
}
[HttpGet]
public ActionResult GetCities(int id)
{
using (var db = new DataEntities())
{
var data = db.Cities.Where(d=>d.StateId==id).Select(d => new { Text = d.CityName, Value = d.Id }).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
public ActionResult SavePersonDetail([Bind(Exclude = "Id")] Person model)
{
// var employeeDal= new Emploee();
//employee.firstname=model.
if (ModelState.IsValid)
{
var Id = model.Id;
int.TryParse(Request["Id"], out Id);
using (var db = new DataEntities())
{
if (Id > 0)
{
var person = db.People.FirstOrDefault(d => d.Id == Id);
if (person != null)
{
model.Id = Id;
db.People.ApplyCurrentValues(model);
}
}
else
{
db.People.AddObject(model);
}
db.SaveChanges();
}
}
if (!Request.IsAjaxRequest())
{
ViewBag.States = GetStates();
ViewBag.Persons = GetPersons();
ViewBag.Cities = Enumerable.Empty<SelectListItem>();
return View("Index");
}
else
{
return PartialView("_personDetail",GetPersons());
}
}
public ActionResult Delete(int id)
{
using (var db = new DataEntities())
{
var model = db.People.FirstOrDefault(d => d.Id == id);
if (model != null)
{
db.People.DeleteObject(model);
db.SaveChanges();
}
}
if (Request.IsAjaxRequest())
{
return Content(id.ToString());
}
else
{
ViewBag.States = GetStates();
ViewBag.Persons = GetPersons();
ViewBag.Cities = Enumerable.Empty<SelectListItem>();
return View("Index");
}
}
private IEnumerable<SelectListItem> GetStates()
{
using (var db = new DataEntities())
{
return db.States.ToList().Select(d => new SelectListItem { Text = d.StateName, Value =d.Id.ToString() });
}
}
private IEnumerable<Person> GetPersons()
{
using (var db = new DataEntities())
{
return db.People.Include("City").Include("City.State").ToList();
}
}
public ActionResult HomeAjax()
{
ViewBag.States = GetStates();
ViewBag.Cities = Enumerable.Empty<SelectListItem>();
using (var db = new DataEntities())
{
var data = db.States.Include("Cities").Select(d => new { Id = d.Id, Name = d.StateName, Cities = d.Cities.Select(x => new { Id=x.Id,Name=x.CityName}) }).ToList();
ViewBag.CityStateJson = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(data);
}
ViewBag.Persons = GetPersons();
return View();
}
}
#model IEnumerable<Person>
<div>
<table>
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Email
</th>
<th>
City
</th>
<th>
State
</th>
<th>
Edit
</th>
</tr>
#if (Model.Count() == 0)
{
<tr>
<td colspan="6">
<h3>No data available</h3>
</td>
</tr>
}
else {
foreach (var item in Model) {
<tr data-id="#item.Id">
<td data-id="fn">#item.FirstName</td>
<td data-id="ln">#item.LastName</td>
<td data-id="email">#item.Email</td>
<td data-id="cn">#item.CityName<input type="hidden" value="#item.CityId" /></td>
<td>#item.StateName</td>
<td>
#if (ViewBag.Title == "Home Ajax" || Request.IsAjaxRequest())
{
Update
<span>#Ajax.ActionLink("Delete", "Delete", new { id = item.Id }, new AjaxOptions {OnSuccess="deleteSuccess",OnBegin="showLoader",OnComplete="hideLoader" })</span>
}
else {
<span>#Html.ActionLink("Update", "Index", new { id = item.Id })</span>
<span>#Html.ActionLink("Delete", "Delete", new { id = item.Id })</span>
}
</td>
</tr>
}
}
</table>
</div>
#model Person
#{
ViewBag.Title = "Home Ajax";
IEnumerable<Person> persons = ViewBag.Persons;
IEnumerable<SelectListItem> States = ViewBag.States;
IEnumerable<SelectListItem> Cities = ViewBag.Cities;
IEnumerable<State> fullStates=ViewBag.CityStates;
}
#section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>#ViewBag.Title.</h1>
</hgroup>
</div>
</section>
}
#section styles{
<style type="text/css">
td,th {
border:1px solid;
padding:5px 10px;
}
select {
padding:5px 2px;
width:310px;
font-size:16px;
}
</style>
}
#section scripts{
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
var jsonArray = #Html.Raw(ViewBag.CityStateJson)
function clearValues() {
$("input[type='text'],select").val('');
$("input[type='hidden'][name='Id']").val(0);
}
function loadCities(obj) {
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].Id == parseInt($(obj).val())) {
fillCity(jsonArray[i].Cities);
break;
}
}
}
function Edit(obj, Id) {
// alert("hi")
$("input[type='hidden'][name='Id']").val(Id);
var tr = $(obj).closest("tr");
$("#txtfirstName").val($("td[data-id='fn']", tr).text().trim());
$("#txtlastName").val($("td[data-id='ln']", tr).text().trim());
$("#txtemail").val($("td[data-id='email']", tr).text().trim());
var city = $("td[data-id='cn'] input[type='hidden']", tr).val();
var state;
for (var i = 0; i < jsonArray.length; i++) {
for (var j = 0; j < jsonArray[i].Cities.length; j++) {
if (jsonArray[i].Cities[j].Id == parseInt(city)) {
state = jsonArray[i].Id;
break;
}
}
if (state) {
fillCity(jsonArray[i].Cities);
break;
}
}
$("#ddlState").val(state);
$("#ddlCity").val(city);
}
function fillCity(obj) {
var html = '<option value="0">Select City</option>';
$(obj).each(function () {
html += '<option value="' + this.Id + '">' + this.Name + '</option>'
});
$("#ddlCity").html(html);
}
function deleteSuccess(responce) {
alert("record deleted successfully");
$("tr[data-id='" + responce + "']").remove();
}
function insertSuccess() {
alert("Record saved successfully");
clearValues();
}
function showLoader() {
$("#overlay").show();
}
function hideLoader() {
$("#overlay").hide();
}
</script>
}
<h3>Add Personal Detail</h3>
#using (Ajax.BeginForm("SavePersonDetail", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "personList" ,OnSuccess="insertSuccess",OnBegin="showLoader",OnComplete="hideLoader"}))
{
#Html.HiddenFor(m => m.Id);
<ol class="round">
<li>
#Html.LabelFor(m => m.FirstName)
#Html.TextBoxFor(m => m.FirstName, new { id = "txtfirstName" })
#Html.ValidationMessageFor(m => m.FirstName)
</li>
<li>
#Html.LabelFor(m => m.LastName)
#Html.TextBoxFor(m => m.LastName, new { id = "txtlastName" })
#Html.ValidationMessageFor(m => m.LastName)
</li>
<li>
#Html.LabelFor(m => m.Email)
#Html.TextBoxFor(m => m.Email, new { id = "txtemail" })
#Html.ValidationMessageFor(m => m.Email)
</li>
<li>
#Html.Label("State")
#Html.DropDownList("State", States, "Select State", new { onchange = "loadCities(this)", id = "ddlState" })
</li>
<li>
#Html.LabelFor(m => m.CityId)
#Html.DropDownListFor(m => m.CityId, Cities, "Select City", new { id = "ddlCity" })
#Html.ValidationMessageFor(m => m.CityId)
</li>
</ol>
<input type="submit" value="Save" />
<input type="button" value="Cancel" onclick="clearValues();"/>
}
<h2>
Person List
</h2>
<div style="position:fixed;text-align:center;top:0;bottom:0;left:0;right:0;z-index:10;background-color:black;opacity:0.6;display:none;" id="overlay">
<img style="position:relative;top:370px" src="~/Images/ajax-loader.gif" />
</div>
<div id="personList">
#Html.Partial("_personDetail", persons)
</div>
You approach using ajax is fine although I would recommend a few better practices including using a view model with properties for StateID, CityID StateList and CityList, and using Unobtrusive JavaScript rather than polluting you markup with behavior, and generating the first ("please select") option with a null value rather than 0 so it can be used with the [Required] attribute
HTML
#Html.DropDownList(m => m.StateID, States, "Select State") // remove the onchange
#Html.DropDownListFor(m => m.CityID, Cities, "Select City") // why change the default ID?
SCRIPT
var url = '#Url.Action("GetCities", "Home")'; // use the helper (dont hard code)
var cities = $('#CityID'); // cache the element
$('#StateID').change(function() {
$.getJSON(url, { id: $(this).val() }, function(response) {
// clear and add default (null) option
cities.empty().append($('<option></option>').val('').text('Please select'));
$.each(response, function(index, item) {
cities.append($('<option></option>').val(item.Value).text(item.Text));
});
});
});
If you were rendering multiple items (say you were asking the user to select their last 10 cities they visited), you can cache the result of the first call to avoid repeated calls where their selections may include cities from the same state.
var cache = {};
$('#StateID').change(function() {
var selectedState = $(this).val();
if (cache[selectedState]) {
// render the options from the cache
} else {
$.getJSON(url, { id: selectedState }, function(response) {
// add to cache
cache[selectedState] = response;
.....
});
}
});
Finally, in response to your comments regarding doing it without ajax, you can pass all the cities to the view and assign them to a javascript array. I would only recommend this if you have a few countries, each with a few cities. Its a matter of balancing the slight extra initial load time vs the slight delay in making the ajax call.
In the controller
model.CityList = db.Cities.Select(d => new { City = d.CountryID, Text = d.CityName, Value = d.Id }).ToList();
In the view (script)
// assign all cities to javascript array
var allCities= JSON.parse('#Html.Raw(Json.Encode(Model.CityList))');
$('#StateID').change(function() {
var selectedState = $(this).val();
var cities = $.grep(allCities, function(item, index) {
return item.CountryID == selectedState;
});
// build options based on value of cities
});
This is a correct approach, but you can simplify your javascript:
function loadCities(obj) {
$.getJSON("/Home/GetCities", function (data) {
var html = '<option value="0">Select City</option>';
$(data).each(function () {
html += '<option value="'+this.Value+'">'+this.Text+'</option>'
});
$("#ddlCity").html(html);
});
}
Further possible simplification:
Add the default item (Select City) server-side, so your javascript will be smaller.
Here's how I'd do it without the page refresh, assuming the list of cities isn't too long.
I'm assuming you can create a GetStatesAndCities method to return a Dictionary.
public ActionResult Index()
{
Dictionary<string, List<String>> statesAndCities = GetStatesAndCities();
ViewBag.StatesAndCities = Json(statesAndCities);
}
Then in the view:
var states = JSON.parse(#ViewBag.StatesAndCities);
function loadCities(obj) {
var cities = states[$(obj).val()];
var html = '<option value="0">Select City</option>';
$(cities).each(function () {
html += '<option value="'+this.Value+'">'+this.Text+'</option>'
});
$("#ddlCity").html(html);
}
This way when the state is changed the cities field with update immediately with no need for callback.
disclaimer: This is not a code answer, there are plenty other answers.
I think best way to keep yourself happy to seperate UI pages from data => turn them into API calls:
/GetCities
/GetStates
Now you can simply leave the select's empty on Razor rendering the page. And use a Jquery/Bootstrap plugin to create an AJAX select box.
This way when the user stops typing his search, this search string can than be send with the AJAX call (eg: /GetStates?search=test) and then a small result set can be send back to the website.
This gives:
Better separation in serveside code
Better User eXperience.
Smaller page loads (since you no longer send all the options to user when he requests the page, only when he opens the select box).
How about using Knockout?
Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model
You have to use ajax for your cities. But with knockout you dont need to write
var html = '<option value="0">Select City</option>';
$(responce).each(function () {
html += '<option value="'+this.Value+'">'+this.Text+'</option>'});
$("#ddlCity").html(html);
in your javascript.Knockout makes it simple.
You can simply write:
function CityModel() {
var self = this; // that means this CityModel
self.cities = ko.observableArray([]);
self.getCities = function () {
$.ajax({
url: "/Home/GetCities",
data: { id: $(obj).val() },
contentType: "application/json",
success: self.cities
});
}
}
ko.applyBindings(new CityModel());
thats all. But you have to bind your data into html elements.
Instead of using :
#Html.DropDownListFor(m => m.CityId, Cities, "Select City", new { id="ddlCity"})
You can use:
<select data-bind="options:cities,optionsValue:"Id",optionsText:"CityName",optionsCaption:"Select City""></select>
or you can mix razor and knockout:
#Html.DropDownListFor(m => m.CityId, Cities, "Select City", new { id="ddlCity",data_bind:"options:cities,optionsValue:\"Id\",optionsText:\"CityName\""})
One more thing you have to call GetCities when State changes, you can :
#Html.DropDownList("State", States, "Select State", new {data_bind:"event:\"change\":\"$root.GetCities\""})
Dont be scare with \"\" things this because " is an escape character and we have to say to razor i want to use " by using \ before it.
You can find more info about knockout :Knockout
And mixing with razor: Razor and Knockout
Ps: yes using knockout is suspend us from Razor and Mvc. You have to write another ViewModel . But like this situations ko is helpful. Mixing razor and knockout is another option for you.

MVC Paging not working in AJAX Form

I am trying to implement ASP.NET MVC Paging using MVC4.Paging nuget package.
Problem:
It is working in online demo and also in the download source code. However I am not able to find why it is not working in my particular project by AJAX. In my project it is working by full post back method but not Ajax.
I have even tried to copy over the Index action method and Index and _AjaxEmployeeList Views (.cshtml) files (except .js).
Note: In my solution its not bootstrap as shown in samples. Also my controller name is AdminController whereas in Samples its HomeController
In my solution I need it to work in AJAX method as in samples.
Kindly help regarding:
1. How to find the root cause for why it is not working?
2. How to make this working?
.
My Solution Code (which I tried to reproduce in my solution from the sample):
Index.cshtml
#using MvcPaging
#model IPagedList<MvcPagingDemo.Models.Employee>
#{
ViewBag.Title = "MVC 4 Paging With Ajax Bootstrap";
}
<div class="row-fluid">
<div class="span6">
<h2>
Ajax Paging With Bootstrap In MVC 4
</h2>
</div>
<div class="span6">
<div class="alert alert-info">
The pager also supports area's. #Html.ActionLink("Ajax paging in an area", "Index", "Admin", new { Area = "AreaOne" }, new { #class = "btn btn-success" })</div>
</div>
</div>
<div class="clearfix">
</div>
#using (Ajax.BeginForm("Index", "Admin",
new AjaxOptions { UpdateTargetId = "grid-list", HttpMethod = "get", LoadingElementId = "loading", OnBegin = "beginPaging", OnSuccess = "successPaging", OnFailure = "failurePaging" },
new { id = "frm-search" }))
{
<div class="input-append">
<input class="span2" id="appendedInputButton" type="text" name="employee_name" placeholder="Name" />
<button class="btn" type="submit">
<i class="icon-search"></i> Search</button>
</div>
<div id="grid-list">
#{ Html.RenderPartial("_AjaxEmployeeList", Model); }
</div>
}
<script type="text/javascript">
function beginPaging(args) {
// Animate
$('#grid-list').fadeOut('normal');
}
function successPaging() {
// Animate
$('#grid-list').fadeIn('normal');
$('a').tooltip();
}
function failurePaging() {
alert("Could not retrieve list.");
}
</script>
_AjaxEmployeeList.cshtml
#using MvcPaging
#model IPagedList<MvcPagingDemo.Models.Employee>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>
ID
</th>
<th>
Name
</th>
<th>
Email
</th>
<th>
Phone
</th>
<th>
City
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.ID
</td>
<td>
#item.Name
</td>
<td>
#item.Email
</td>
<td>
#item.Phone
</td>
<td>
#item.City
</td>
</tr>
}
</tbody>
</table>
<div class="pager1">
#Html.Raw(Ajax.Pager(
new Options
{
PageSize = Model.PageSize,
TotalItemCount = Model.TotalItemCount,
CurrentPage = Model.PageNumber,
ItemTexts = new ItemTexts() { Next = "Next", Previous = "Previous", Page = "P" },
ItemIcon = new ItemIcon() { First = "icon-backward", Previous = "icon-chevron-left", Next = "icon-chevron-right", Last = "icon-forward" },
TooltipTitles = new TooltipTitles() { Next = "Next page", Previous = "Previous page", Page = "Page {0}." },
Size = Size.normal,
Alignment = Alignment.centered,
IsShowControls = true,
IsShowFirstLast = true,
CssClass = ""
},
new AjaxOptions
{
UpdateTargetId = "grid-list",
OnBegin = "beginPaging",
OnSuccess = "successPaging",
OnFailure = "failurePaging"
}, new { controller = "Admin", action = "Index", employee_name = ViewData["employee_name"] }))
<div class="well">
Showing <span class="badge badge-success">#Model.ItemStart</span> to <span class="badge badge-success">#Model.ItemEnd</span>
of <span class="badge badge-info">#Model.TotalItemCount</span> entries</div>
</div>
AdminController.cs
public class AdminController : Controller
{
private const int defaultPageSize = 3;
private IList<Employee> allEmployee = new List<Employee>();
private string[] name = new string[4] { "Will", "Johnny", "Zia", "Bhaumik" };
private string[] phone = new string[4] { "1-274-748-2630", "1-762-805-1019", "1-920-437-3485", "1-562-653-8258" };
private string[] email = new string[4] { "donec#congueelitsed.org", "neque.non#Praesent.co.uk", "et.magna#Pellentesque.ca", "enim.commodo#orci.net" };
private string[] city = new string[4] { "Wigtown", "Malderen", "Las Vegas", "Talence" };
public AdminController()
{
InitializeEmployee();
}
private void InitializeEmployee()
{
// Create a list of 200 employee.
int index = 0;
for (int i = 0; i < 200; i++)
{
var employee = new Employee();
//int categoryIndex = i % new Random().Next(1, 5);
//if (categoryIndex > 3)
// categoryIndex = 3;
index = index > 3 ? 0 : index;
employee.ID = i + 1;
employee.Name = name[index];
employee.Phone = phone[index];
employee.Email = email[index];
employee.City = city[index];
allEmployee.Add(employee);
index++;
}
}
public ActionResult Index(string employee_name, int? page)
{
ViewData["employee_name"] = employee_name;
int currentPageIndex = page.HasValue ? page.Value : 1;
IList<Employee> employees = this.allEmployee;
if (string.IsNullOrWhiteSpace(employee_name))
{
employees = employees.ToPagedList(currentPageIndex, defaultPageSize);
}
else
{
employees = employees.Where(p => p.Name.ToLower() == employee_name.ToLower()).ToPagedList(currentPageIndex, defaultPageSize);
}
//var list =
if (Request.IsAjaxRequest())
return PartialView("_AjaxEmployeeList", employees);
else
return View(employees);
}
public ActionResult Paging(string employee_name, int? page)
{
ViewData["employee_name"] = employee_name;
int currentPageIndex = page.HasValue ? page.Value : 1;
IList<Employee> employees = this.allEmployee;
if (string.IsNullOrWhiteSpace(employee_name))
{
employees = employees.ToPagedList(currentPageIndex, defaultPageSize);
}
else
{
employees = employees.Where(p => p.Name.ToLower() == employee_name.ToLower()).ToPagedList(currentPageIndex, defaultPageSize);
}
return View(employees);
}
}
JS references in the _Layout.cshtml
You have not described how exactly it is not working. but i will guess the most common issues which might be causing your issue
make sure you actually have a reference to the correct java script files. its not enough to have them in a folder, your page must link to them.
see the following link to see how you reference scripts on you page. http://www.w3schools.com/tags/att_script_src.asp
make sure you put in the correct path.
make sure you reference the *ajax.js files for ajax to work along with any other required files.
Finally I found the solution.
Since I was using jquery-1.11.1.js, in script file jquery.unobtrusive-ajax.js I had to replace calls to .live() with .on().
But simple find and replace was not right way which I found later. I found from other sources that I have to change completely those lines of code as the .on() works.
I replaced the code as below:
Non-working code with .live() function:
$("a[data-ajax=true]").live("click", function (evt) {
debugger;
evt.preventDefault();
asyncRequest(this, {
url: this.href,
type: "GET",
data: []
});
});
$("form[data-ajax=true] input[type=image]").live("click", function (evt) {
debugger;
var name = evt.target.name,
$target = $(evt.target),
form = $target.parents("form")[0],
offset = $target.offset();
$(form).data(data_click, [
{ name: name + ".x", value: Math.round(evt.pageX - offset.left) },
{ name: name + ".y", value: Math.round(evt.pageY - offset.top) }
]);
setTimeout(function () {
$(form).removeData(data_click);
}, 0);
});
$("form[data-ajax=true] :submit").live("click", function (evt) {
debugger;
var name = evt.target.name,
form = $(evt.target).parents("form")[0];
$(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []);
setTimeout(function () {
$(form).removeData(data_click);
}, 0);
});
$("form[data-ajax=true]").live("submit", function (evt) {
debugger;
var clickInfo = $(this).data(data_click) || [];
evt.preventDefault();
if (!validate(this)) {
return;
}
asyncRequest(this, {
url: this.action,
type: this.method || "GET",
data: clickInfo.concat($(this).serializeArray())
});
});
Working code with .on() function:
$(document).on("click", "a[data-ajax=true]", function (evt) {
evt.preventDefault();
asyncRequest(this, {
url: this.href,
type: "GET",
data: []
});
});
$(document).on("click", "form[data-ajax=true] input[type=image]", function (evt) {
var name = evt.target.name,
$target = $(evt.target),
form = $target.parents("form")[0],
offset = $target.offset();
$(form).data(data_click, [
{ name: name + ".x", value: Math.round(evt.pageX - offset.left) },
{ name: name + ".y", value: Math.round(evt.pageY - offset.top) }
]);
setTimeout(function () {
$(form).removeData(data_click);
}, 0);
});
$(document).on("click", "form[data-ajax=true] :submit", function (evt) {
var name = evt.target.name,
form = $(evt.target).parents("form")[0];
$(form).data(data_click, name ? [{ name: name, value: evt.target.value }] : []);
setTimeout(function () {
$(form).removeData(data_click);
}, 0);
});
$(document).on("submit", "form[data-ajax=true]", function (evt) {
var clickInfo = $(this).data(data_click) || [];
evt.preventDefault();
if (!validate(this)) {
return;
}
asyncRequest(this, {
url: this.action,
type: this.method || "GET",
data: clickInfo.concat($(this).serializeArray())
});
});
Thanks.

Categories

Resources