How to show No have any Data message in List view page if no have any record in the database.
This is my ICouponRepository interface to inject in this controller.
IEnumerable<ManuItem> GetAllManuItem();
This is my SQLManuItemRepository to inherit ICouponRepository
public IEnumerable<ManuItem> GetAllManuItem()
{
try
{
return context.ManuItems.Include(mi => mi.Category)
.Include(mi => mi.SubCategory)
.Where(mi => mi.IsDelete == false);
}
catch (Exception ex)
{
var exception = ex.Message;
return null;
}
}
This is my Controller method
public IActionResult Index()
{
try
{
var model = manuItemRepository.GetAllManuItem();
if (model == null)
{
ViewBag.NoData = "No have any Data";
return View();
}
return View(model);
}
catch (Exception ex)
{
ViewBag.Error = "Somthing was Worng" + ex.Message;
}
return View();
}
Any change in this method or change in View?
You can directly judge whether the returned model has data on the view. You can refer to the modified code below.
Controller
public IActionResult Index()
{
var model = new List<ManuItem>();
try
{
model = manuItemRepository.GetAllManuItem();
}
catch (Exception ex)
{
ViewBag.Error = "Somthing was Worng" + ex.Message;
}
return View(model);
}
View
#if (Model.Count() == 0)
{
<p>No have any Data</p>
}
else
{
<p>Have Data</p>
}
AI am just moving to ASYNC methods and trying to get my data to update. I can select just find so I know the repository is working.
Action
[HttpPost]
public async Task<IActionResult> EditTeam(EmployeeVm empVm)
{
if (!ModelState.IsValid)
{
ModelState.AddModelError("", _errorUpdateMsg);
}
else
{
if (await _teamRepository.UpdateEmployee(empVm.Employee))
{
return RedirectToAction("Index");
}
ModelState.AddModelError("", _errorUpdateMsg);
}
return View(empVm);
}
My Constructor in repo
public TeamRepository(EnvisionDbContext envisionDbContext)
{
_envisonDbContext = envisionDbContext;
}
Here is my Update that does not save
public async Task<bool> UpdateEmployee(Employee employee)
{
var result = await _envisonDbContext.Employees.FirstOrDefaultAsync<Employee>(e => e.Id == employee.Id);
if (result != null)
{
result.FirstName = employee.FirstName;
result.LastName = employee.LastName;
result.Phone = employee.Phone;
result.IsActive = employee.IsActive;
await _envisonDbContext.SaveChangesAsync();
return true;
}
return false;
}
Thanks in advance for the help.
UPDATED: If I add this, it works. Is this because the two await calls are disconnected?
result.IsActive = employee.IsActive;
_envisonDbContext.Entry(result).State = EntityState.Modified;
Seems like you forgot update-method before savingchanges
if (result != null)
{
result.FirstName = employee.FirstName;
result.LastName = employee.LastName;
result.Phone = employee.Phone;
result.IsActive = employee.IsActive;
_envisionDbContext.Update(result); //paste it before you save changes
await _envisonDbContext.SaveChangesAsync();
return true;
}
In my ASP.NET Core 3.1 web application, I am mostly using stored procedures. When using ExecuteSqlRawAsync in Entity Framework Core it always returns -1. Below given is my generalized method to execute stored procedures.
public async Task<int> ExecuteSqlNonQuery(string StoredProcName, params object[] parameters)
{
int iTotalRecordsAffected = 0;
List<TEntity> listOfObject = null;
try
{
if (!string.IsNullOrEmpty(StoredProcName))
{
StringBuilder sbStoredProc = new StringBuilder();
sbStoredProc.Append("Exec ");
sbStoredProc.Append(StoredProcName);
if (parameters != null)
{
foreach (SqlParameter item in parameters)
{
if (listOfObject == null)
{
sbStoredProc.Append(" #");
listOfObject = new List<TEntity>();
}
else
{
sbStoredProc.Append(", #");
}
sbStoredProc.Append(item.ParameterName.Replace("#", ""));
if (item.Direction == System.Data.ParameterDirection.Output)
{
sbStoredProc.Append(" OUT");
}
}
}
iTotalRecordsAffected = await _DBContext.Database.ExecuteSqlRawAsync(sbStoredProc.ToString(), parameters);
}
}
catch (Exception ex)
{
}
finally
{
if (_DBContext.Database.GetDbConnection().State == System.Data.ConnectionState.Open)
{
_DBContext.Database.GetDbConnection().Close();
}
}
return iTotalRecordsAffected;
}
Here is my controller method that calls a SP to update data.
public async Task<int> UpdateCustomerData(EditCustomerDetail editCustomerDetail)
{
int iTotalRecordsEffected = 0;
try
{
List<SqlParameter> sqlParamList = new List<SqlParameter>()
{
new SqlParameter("#CustomerID",editCustomerDetail.CorporateID),
new SqlParameter("#CustomerName",editCustomerDetail.CorporateName),
new SqlParameter("#CustomerAddress",editCustomerDetail.Address),
new SqlParameter("#City",editCustomerDetail.City),
new SqlParameter("#CountryID",editCustomerDetail.CountryID),
new SqlParameter("#StateID",editCustomerDetail.StateID),
new SqlParameter("#Description",editCustomerDetail.Description),
new SqlParameter("#Phone",editCustomerDetail.Phone),
new SqlParameter("#Fax",editCustomerDetail.Fax),
new SqlParameter("#ModifiedBy",editCustomerDetail.UserID)
};
iTotalRecordsEffected = await _unitOfWork.GetRepository<EditCustomerDetail>().ExecuteSqlNonQuery("UpdateCustomerDetails", sqlParamList.ToArray());
}
catch (Exception ex)
{
}
finally
{
}
return iTotalRecordsEffected;
}
Any suggestion what I am doing wrong?
i used Rotativa to print one of my page from html to pdf and when i hit the button to print,it will open print preview,but the preview does not contains that page i just print , it contains and show me log in page in preview instead as you can see,so idont know exactly whats happend.Can someone please point me in the right direction?
The page i tried to print look like this:
But when i hit the button to print,in preview give me log in page:
AccountController:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (Session["CustomerID"] == null &! Request.RawUrl.ToLower().Contains("login"))
{
Response.Redirect("/Account/Login");
}
base.OnActionExecuting(filterContext);
}
<br>
//Login
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(Customers cust)
{
using (DataContext db = new DataContext())
{
var user = db.Customers.Where(u => u.CustomerID == cust.CustomerID).FirstOrDefault();
if (user != null)
{
Session["CustomerID"] = user.CustomerID.ToString();
FormsAuthentication.SetAuthCookie(cust.CustomerID, false);
Session.Timeout = 30;
return RedirectToAction("LoggedIn");
}
else
{
ModelState.AddModelError("", "CustomerID is not Valid");
}
}
return View();
}
public ActionResult LoggedIn()
{
if (Session["CustomerID"] != null)
{
string customerId = Session["CustomerID"].ToString();
List<Orders> customerOrders;
using (DataContext data = new DataContext())
{
customerOrders = data.Orders.Where(x => x.CustomerID == customerId).ToList();
}
return View(customerOrders);
}
else
{
return RedirectToAction("Login");
}
}
public ActionResult Logout()
{
FormsAuthentication.SignOut();
Session.Remove("Login");
return RedirectToAction("Login", "Account");
}
public ActionResult PrintOrders(int id)
{
var report = new ActionAsPdf("ShowOrdersDetails", new { id = id });
return report;
}
My Controller in which there are different actions for different views
// GET: Employee
public ActionResult Index)
{
List<EmployeeViewModel> Employees = null;
Employees = _DaoEmployee.FindAll();
ViewData["model"] = Employees;
return View(Employees);
}
public ActionResult Details(int id)
{
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
employee emp = _DaoEmployee.ViewEmployee(id);
return View(emp);
}
[HttpGet]
public ActionResult Create()
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
return View();
}
// POST: Employee
[HttpPost]
// public async Task<ActionResult> Create(employee emp, HttpPostedFileBase file)
// public ActionResult Create(employee emp, HttpPostedFileBase file)
public async Task<ActionResult> Create(employee emp, HttpPostedFileBase file)
{
string path = null;
emp.createdby = Convert.ToInt32(Sessions.GetSession()[0]);
emp.createddate = DateTime.Now;
emp.updatedby = Convert.ToInt32(Sessions.GetSession()[0]);
emp.updateddate = DateTime.Now;
int empid = _DaoEmployee.AddEmployee(emp);
if (empid == -1)
{
return HttpNotFound();
}
if (empid >= 1)
{
//Insert User
// string image = System.IO.Path.GetFileName(file.FileName);
if (file != null)
{
var newPath = DateTime.Now.ToString("yyyymmddMMss") + file.FileName;
path = Server.MapPath("~/Content/images/" + newPath);
file.SaveAs(path);
}
string sub = "Your Password";
cms_user u = new cms_user();
u.user_name = emp.emp_name;
u.user_image = path;
u.user_email = emp.email;
u.user_password = RandomPassword.CreatePassword();
u.entity_id = empid;
u.entity_type = "Employee";
u.user_description = emp.comment;
var pass = "Your Password is " + u.user_password;
bool result = _DaoUser.AddUser(u);
if (result == true)
{
emp_performance ep = new emp_performance();
var designation = _DaoEmployee.GetEmployeeDesignationName(emp.desig_id);
ep.emp_perf_des = "Start Working As " + designation;
ep.emp_perf_date = DateTime.Now;
ep.emp_id = empid;
bool res = _DaoEmployee.AddEmployeePerformance(ep);
if (res == true)
{
await Email.sendEmail(u.user_name, u.user_email, pass, sub);
TempData["add"] = emp.emp_name + " is Added and Email Sent Succesfully !!!";
return RedirectToAction("Index", "Employee");
}
else
{
TempData["add"] = emp.emp_name + " is Added Succesfully But Email Not Sent !!!";
return RedirectToAction("Index", "Employee");
}
}
else
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
TempData["error"] = "Error !!! Employee is not Added";
return View();
}
}
else
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
TempData["error"] = "Error !!! Employee is not Added";
return View();
}
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name");
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name");
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name");
TempData["error"] = "Error !!! Employee is not Added";
return View();
}
//Get
[HttpGet]
public ActionResult Edit(int id)
{
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
employee emp = _DaoEmployee.FindEmployee(id);
if (emp != null)
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name", _db.employees.FirstOrDefault(q => q.emp_id == id).desig_id);
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_status_id);
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_alternative_relationship);
return View(emp);
}
else
return HttpNotFound();
}
// POST: Employee
[HttpPost]
public ActionResult Edit(employee emp)
{
var id = emp.emp_id;
emp.email = "example#gmail.com";
emp.updatedby = emp.createdby = Convert.ToInt32(Sessions.GetSession()[0]);
emp.updateddate = DateTime.Now;
bool result = _DaoEmployee.EditEmployee(emp);
if (result == true)
{
TempData["update"] = emp.emp_name + " is Updated Succesfully !!!";
return RedirectToAction("Index", "Employee");
}
else
{
ViewBag.desig_id = new SelectList(_db.designations, "desg_id", "desg_name", _db.employees.FirstOrDefault(q => q.emp_id == id).desig_id);
ViewBag.emp_status_id = new SelectList(_db.emp_status, "emp_status_id", "emp_status_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_status_id);
ViewBag.emp_alternative_relationship = new SelectList(_db.emp_alternative, "rel_name", "rel_name", _db.employees.FirstOrDefault(q => q.emp_id == id).emp_alternative_relationship);
TempData["error"] = "Error !!! Employee is not Updated";
return View();
}
}
// DELETE: Employee
public ActionResult Delete(int id)
{
var name = _db.employees.FirstOrDefault(q => q.emp_id == id).emp_name;
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
else
{
if (id != 0)
{
bool result = _DaoEmployee.DeleteEmployee(id);
if (result == true)
{
TempData["delete"] = name + " is Deleted Succesfully !!!";
return RedirectToAction("Index", "Employee");
}
}
}
TempData["error"] = "Error !!! User is not Deleted";
return RedirectToAction("Index", "Employee");
}
//protected override void Dispose(bool disposing)
//{
// if (disposing)
// {
// _db.Dispose();
// }
// base.Dispose(disposing);
//}
public ActionResult Profile()
{
if (!Sessions.IsEmployeeLoggedIn())
{
return View();
}
int user_id = Convert.ToInt32(Sessions.GetSession()[0]);
int id = Convert.ToInt32(Sessions.GetSession()[5]);
ViewBag.user_password = _db.cms_user.FirstOrDefault(q => q.user_id == user_id).user_password;
cms_user user = _DaoUser.FindUser(id);
//Get employee perfomance history from tbl performance
List<emp_performance> emp_his = _DaoEmployee.FindHistory(id);
ViewData["JoBHistory"] = emp_his;
//Attendance Of Employee
List<attendance> att = _DaoAttendance.FindById(id);
ViewData["attendance"] = att;
//Projects on which employee working
List<ProjectTeamModel> team = _DaoProject.FindProjectById(id);
ViewData["projteam"] = team;
//Get Employee Designation from tbl emp
int designation = _DaoEmployee.GetEmployeeDesignation(id);
ViewBag.EmployeeDesignation = _DaoEmployee.GetEmployeeDesignationName(designation);
employee emp = _db.employees.Where(e => e.emp_id == id).FirstOrDefault();
return View(emp);
}
public ActionResult Dashboard()
{
if (!Sessions.IsAdminLoggedIn())
{
return View();
}
ViewBag.image = Sessions.GetSession()[2];
int id = Convert.ToInt32(Sessions.GetSession()[5]);
employee emp = _db.employees.Where(e => e.emp_id == id).FirstOrDefault();
return View(emp);
}
public ActionResult ViewAttendance(int id)
{
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
List<attendance> att = _DaoAttendance.FindById(id);
if (att != null)
{
return View(att);
}
else
return HttpNotFound();
}
public ActionResult ViewProjects(int id)
{
if (!Sessions.IsAdminLoggedIn())
{
return RedirectToAction("Login", "Account");
}
List<ProjectTeamModel> team = _DaoProject.FindProjectById(id);
ViewData["projteam"] = team;
if (team != null)
{
return View();
}
else
return HttpNotFound();
return View();
}
public ActionResult JobHistory(int id)
{
List<emp_performance> emp_his = _DaoEmployee.FindHistory(id);
ViewData["model"] = emp_his;
return View(emp_his);
}
public ActionResult AddDesignation()
{
string desg = Request.Form["emp_desg"];
bool result = _DaoEmployee.AddDesignation(desg);
if (result == true)
{
return RedirectToAction("Dashboard", "Employee");
}
else
return HttpNotFound();
}
public ActionResult DesignationList(int Id)
{
if (Id == 1)
{
IEnumerable<emp_status> status = _db.emp_status.ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
status,
"emp_status_id",
"emp_status_name"), JsonRequestBehavior.AllowGet
);
return View(status);
}
if (Id == 2)
{
IEnumerable<designation> status = _db.designations.ToList();
if (HttpContext.Request.IsAjaxRequest())
return Json(new SelectList(
status,
"desg_id",
"desg_name"), JsonRequestBehavior.AllowGet
);
return View(status);
}
return View("Index");
}
[HttpPost]
public ActionResult MarkAttendance(attendance att)
{
att.Date = DateTime.Now;
int Id = Convert.ToInt32(Sessions.GetSession()[5]);
att.emp_id = Id;
bool result = _DaoAttendance.AddEmployeeAttendance(att);
if (result == true)
{
return RedirectToAction("Profile", "Employee");
}
else
{
return RedirectToAction("Profile", "Employee");
}
}
public ActionResult EditUser(cms_user user, HttpPostedFileBase file)
{
string path = Sessions.GetSession()[3];
if (file != null)
{
var newPath = DateTime.Now.ToString("yyyymmddMMss") + file.FileName;
path = Server.MapPath("~/Content/images/" + newPath);
file.SaveAs(path);
}
user.user_image = path;
user.user_id = Convert.ToInt32(Sessions.GetSession()[0]);
user.entity_id = Convert.ToInt32(Sessions.GetSession()[5]);
user.entity_type = Sessions.GetSession()[4];
//user.user_description = Request.Form["user_description"];
bool result = _DaoUser.EditUser(user);
if (result == true)
{
return RedirectToAction("Profile", "Employee");
}
else
{
return RedirectToAction("Profile", "Employee");
}
}
public ActionResult AddPerformance(emp_performance ep)
{
var name = _db.employees.FirstOrDefault(q => q.emp_id == ep.emp_id).emp_name;
ep.emp_perf_date = DateTime.Now;
bool result = _DaoEmployee.AddEmployeePerformance(ep);
if (result == true)
{
TempData["add"] = "Perfomnace of " + name + " Added Successfully !!!";
return RedirectToAction("Index", "Employee");
}
else
{
TempData["error"] = "Error !!! Employee Performance is not Added";
return RedirectToAction("Index", "Employee");
}
}
}
Class Libraray Class
public class DaoEmployee
{
CmsdbEntities _db = new CmsdbEntities();
public List<EntityFramework.employee> FindAllEmployee()
{
try
{
var records = from r in _db.employees
select r;
return records.ToList();
}
catch (Exception ex)
{
return new List<EntityFramework.employee>();
}
}
public List<EmployeeViewModel> FindAll()
{
try
{
// Should be check by directly assigning
// the List<employeeV> or IEnumerable<employeeV>
var records = (from r in _db.employees
select new
{
r.emp_id,
r.emp_name,
r.emp_contactno,
r.emp_dob,
r.emp_salary,
r.emp_joindate,
r.emp_address,
emp_designation = _db.designations.FirstOrDefault(q => q.desg_id == r.desig_id).desg_name,
emp_status = _db.emp_status.FirstOrDefault(q => q.emp_status_id == r.emp_status_id).emp_status_name,
createdbyName = _db.cms_user.FirstOrDefault(q => q.user_id == r.createdby).user_name,
r.createddate,
updateddbyName = _db.cms_user.FirstOrDefault(q => q.user_id == r.updatedby).user_name,
r.updateddate
}).ToList();
List<EmployeeViewModel> employees = new List<EmployeeViewModel>();
foreach (var record in records)
{
EmployeeViewModel employee = new EmployeeViewModel();
employee.emp_id = record.emp_id;
employee.emp_name = record.emp_name;
employee.emp_contactno = record.emp_contactno;
employee.emp_dob = record.emp_dob;
employee.emp_salary = record.emp_salary;
employee.emp_joindate = record.emp_joindate;
employee.emp_address = record.emp_address;
employee.emp_designation = record.emp_designation;
employee.emp_status = record.emp_status;
employee.createdbyName = record.createdbyName;
employee.createddate = record.createddate;
employee.updatedbyName = record.updateddbyName;
employee.updateddate = record.updateddate;
employees.Add(employee);
}
return employees;
}
catch (Exception ex)
{
return new List<EmployeeViewModel>();
}
}
public List<ProjectViewModel> FindProjectsByStatus(int j)
{
throw new NotImplementedException();
}
public bool CheckEmployeePerformance(int empid, int projid)
{
try
{
var record = from r in _db.emp_performance
where r.emp_id == empid && r.proj_id == projid
select r;
if (record != null)
return true;
else
return false;
}
catch (Exception ex)
{
return false;
}
}
public object GetEmployeeDesignationName(int? desig_id)
{
return _db.designations.FirstOrDefault(a => a.desg_id == desig_id).desg_name;
}
public employee FindEmployee(int id)
{
return _db.employees.Find(id);
}
public bool EditEmployee(employee emp)
{
try
{
_db.Entry(emp).State = EntityState.Modified;
_db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public int AddEmployee(employee emp)
{
try
{
_db.Entry(emp).State = EntityState.Added;
_db.SaveChanges();
return emp.emp_id;
}
catch (Exception ex)
{
return -1;
}
}
public employee ViewEmployee(int id)
{
return _db.employees.Find(id);
}
public bool DeleteEmployee(int id)
{
try
{
employee emp = _db.employees.Find(id);
_db.employees.Remove(emp);
_db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool AddEmployeePerformance(emp_performance ep)
{
try
{
_db.Entry(ep).State = EntityState.Added;
_db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public List<emp_performance> FindHistory(int id)
{
try
{
var records = from r in _db.emp_performance
where r.emp_id == id
select r;
return records.ToList();
}
catch (Exception ex)
{
return new List<emp_performance>();
}
}
public bool AddDesignation(string desg)
{
designation d = new designation();
d.desg_name = desg;
try
{
_db.Entry(d).State = EntityState.Added;
_db.SaveChanges();
return true;
}
catch (Exception ex)
{
return false;
}
}
public dynamic GetEmployeeDesignation(int id)
{
int? desig = _db.employees.FirstOrDefault(u => u.emp_id == id).desig_id;
return desig;
}
public dynamic GetEmployeeDesignationName(int designation)
{
string desig = _db.designations.Where(u => u.desg_id == designation).FirstOrDefault().desg_name;
return desig;
}
}
What is the benefits of using class library classes, Can anyone explain?