I want to add news in database. When I use this code for Select Category return
Me Null . How can I resolve this?
<select name="category">
#{
foreach (var item in RCat.MainCategory().Where(a=>a.ParentID==1))
{
<option value="#item.ID">#item.Title</option>
}
}
</select>
My Controller :
[HttpPost]
[ValidateInput(false)]
public ActionResult CreateNews(Tbl_News t, HttpPostedFileBase pic, int Category)
{
try
{
if (Session["Username"] == null)
return RedirectToAction("Register", "Home");
if (pic == null)
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . باید عکسی را برای خبر انتخاب کنید";
return View();
}
if (Category == 0)
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . باید یکی از دسته ها را انتخاب کنید";
return View();
}
t.Date = DateTime.Now.Date;
t.Dislike = 0;
t.Like = 0;
t.Visit = 0;
t.Username = Session["Username"].ToString();
if (t.Type != "iran" && t.Type != "world" && t.Type != "sport" && t.Type != "art" && t.Type != "knowledge" && t.Type != "economic" && t.Type != "memo" && t.Type != "you" && t.Type != "pic" && t.Type != "video")
t.Type = null;
if (ModelState.IsValid)
{
if (pic != null)
{
if (pic.ContentLength <= 512000)
{
if (pic.ContentType == "image/jpeg")
{
Random rnd = new Random();
string picname = rnd.Next().ToString();
string path = System.IO.Path.Combine(Server.MapPath("~/Content/img/NewsPic/"));
pic.SaveAs(path + picname);
t.Image = picname;
db.Tbl_News.Add(t);
if (Convert.ToBoolean(db.SaveChanges()))
{
var q = (from a in db.Tbl_News
orderby a.Date descending
select a).FirstOrDefault();
Tbl_Cat_News TCN = new Tbl_Cat_News();
TCN.NewsID = q.ID;
TCN.CatID = Category;
db.Tbl_Cat_News.Add(TCN);
if (Convert.ToBoolean(db.SaveChanges()))
{
ViewBag.Style = "color:green";
ViewBag.Message = "با موفقیت ثبت شد";
return View();
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . خبر ثبت نشد";
return View();
}
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . خبر ثبت نشد";
return View();
}
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . فرمت تصویر باید jpg باشد";
return View();
}
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . حجم تصویر باید بیشتر کمتر از 515 کیلو بایت باشد";
return View();
}
}
else
{
return RedirectToAction("Logout", "Admin");
}
}
else
{
ViewBag.Style = "color:red";
ViewBag.Message = "خطایی رخ داده . تمامی فیلدها باید پر شوند";
return View();
}
}
catch (Exception)
{
return Content("خطا");
}
}
You have all OR condition, so if any type not match with any condition it fires "t.Type = null;" and because of that you always get "NULL" value.
Related
I have a problem in mi code, when show the error message appears the message of the title
This is the code of my form Register
<div class="form-group col-md-6">
#if (!Model.MODEL_PACIENTE.PAC_ID.Equals(0))
{
<label>Comuna:</label>
#Html.DropDownList("MODEL_PACIENTE.PAC_COMUNA", new SelectList(Model.MODEL_PACIENTE.Comuna_Lista, "Text", "Text"),
new { #class = "form-control" })
}
else
{
<label>Comuna:</label>
#Html.DropDownList("MODEL_PACIENTE.PAC_COMUNA", new SelectList(Model.MODEL_PACIENTE.Comuna_Lista, "Text", "Text"),
"ESCOGA UNA COMUNA", new { #class = "form-control" }) // HERE IS THE ERROR WHEN MY DNI IS REGISTER IN THE BD }
<span asp-validation-for="MODEL_PACIENTE.PAC_COMUNA" class="text-danger"></span>
</div>
Code of my class GetOdontologo
public List<SelectListItem> GetOdontologo(ApplicationDbContext context)
{
List<SelectListItem> selectListItems = null;
try
{
selectListItems = new List<SelectListItem>();
context.TBL_ODONTOLOGO.ToList().ForEach(item =>
{
selectListItems.Add(new SelectListItem
{
Value = item.ODONT_ID.ToString(),
// Text = item.ODONT_CODIGO
Text = item.ODONT_CODIGO + '-' + item.ODONT_APELLIDO + ' ' + item.ODONT_NOMBRE
});
});
}
catch (Exception ex)
{
Console.WriteLine($"Error: '{ex}'");
}
return selectListItems;
}
This is the class GetComuna
public List<SelectListItem> GetComuna(ApplicationDbContext context)
{
List<SelectListItem> selectListItems = null;
try
{
selectListItems = new List<SelectListItem>();
context.TBL_PROVINCIA.ToList().ForEach(item =>
{
selectListItems.Add(new SelectListItem
{
Value = item.PROV_ID.ToString(),
Text = item.PROV_NOMBRE
});
});
}
catch (Exception ex)
{
Console.WriteLine($"Error: '{ex}'");
}
return selectListItems;
}
And this the code of my method "onget"
public void OnGet(int idActPac)
{
_DataPac2 = null;
if(idActPac.Equals(0))
{
_DataPac2 = null;
}
if (_dataInput != null || _DataPac1 != null || _DataPac2 != null)
{
if (_dataInput != null)
{
MODEL_PACIENTE = _dataInput;
MODEL_PACIENTE.AvatarImage = null;
}
else
{
if (_DataPac1 != null || _DataPac2 != null)
{
if (_DataPac2 != null)
_DataPac1 = _DataPac2;
MODEL_PACIENTE = new PACIENTE
{
PAC_ID = _DataPac1.PAC_ID,
PAC_NOMBRE = _DataPac1.PAC_NOMBRE,
PAC_APELLIDO = _DataPac1.PAC_APELLIDO,
PAC_CODIGO = _DataPac1.PAC_CODIGO,
PAC_EDAD = _DataPac1.PAC_EDAD,
PAC_COD_ODONT = _DataPac1.PAC_COD_ODONT,
PAC_COMUNA = _DataPac1.PAC_COMUNA,
PAC_CORREO = _DataPac1.PAC_CORREO,
PAC_DIRECCION = _DataPac1.PAC_DIRECCION,
PAC_OBSERVACIONES = _DataPac1.PAC_OBSERVACIONES,
PAC_OTRAS_COMUNAS = _DataPac1.PAC_OTRAS_COMUNAS,
PAC_CONVENIO = _DataPac1.PAC_CONVENIO,
PAC_PREVISIONES = _DataPac1.PAC_PREVISIONES,
PAC_REPRESENTANTE = _DataPac1.PAC_REPRESENTANTE,
PAC_RUT = _DataPac1.PAC_RUT,
PAC_SEXO = _DataPac1.PAC_SEXO,
PAC_TELEFONO = _DataPac1.PAC_TELEFONO,
PAC_FECHA_NAC = _DataPac1.PAC_FECHA_NAC,
PAC_FEC_ACT = _DataPac1.PAC_FEC_ACT,
PAC_FEC_REG = _DataPac1.PAC_FEC_REG,
PAC_IMAGEN = _DataPac1.PAC_IMAGEN,
//AL USAR EL METODO ACTUALIZAR AL CARGAR LOS DATOS EN LOS INPUT NO OLVIDAR QUE SE DEBE CARGAR
//NUEVAMENTE LOS DropDownList LLAMANDOLO NUEVAMENTE AL FINAL COMO SE VE EN EL CODIGO A CONTINUACION
Genero_Lista = _lPacienteGen.GetGenero(_context),
Comuna_Lista = _lComuna.GetComuna(_context),
Odontologo_Lista = _lOdontologo.GetOdontologo(_context)
};
if (_dataInput != null)
{
MODEL_PACIENTE.ErrorMessage = _dataInput.ErrorMessage;
}
}
}
}
else
{
var Cod_Pac = 0;
String TempCodPac = null;
var Ultimo_Paciente = (from t in _context.TBL_PACIENTE
orderby t.PAC_CODIGO
select t).LastOrDefault();
if (Ultimo_Paciente != null)
{
Cod_Pac = (Ultimo_Paciente.PAC_CODIGO != null) ?
Convert.ToInt32(Ultimo_Paciente.PAC_CODIGO) + 1 :
1;
if (Cod_Pac < 10)
{
TempCodPac = String.Concat("0000", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac >= 10 && Cod_Pac <= 11)
{
TempCodPac = String.Concat("000", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac > 10 && Cod_Pac < 100)
{
TempCodPac = String.Concat("000", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac >= 100 && Cod_Pac <=101)
{
TempCodPac = String.Concat("00", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac > 100 && Cod_Pac < 1000)
{
TempCodPac = String.Concat("00", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac >= 1000 && Cod_Pac <= 1001)
{
TempCodPac = String.Concat("0", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac > 1000 && Cod_Pac <= 9999)
{
TempCodPac = String.Concat("0", Convert.ToString(Cod_Pac));
}
else if (Cod_Pac > 9999 && Cod_Pac < 99999)
{
TempCodPac = String.Concat("", Convert.ToString(Cod_Pac));
}
}
MODEL_PACIENTE = new PACIENTE
{
PAC_CODIGO = TempCodPac,
Genero_Lista = _lPacienteGen.GetGenero(_context),
Comuna_Lista = _lComuna.GetComuna(_context),
Odontologo_Lista = _lOdontologo.GetOdontologo(_context),
PAC_COD_ODONT = "00000"
};
}
_DataPac2 = _DataPac1;
_DataPac1 = null;
}
The code of my method Save_Patient
private async Task<bool> Guardar_Paciente_Async()
{
_dataInput = MODEL_PACIENTE;
var valor = false;
if (ModelState.IsValid)
{
var PacLista = _context.TBL_PACIENTE.Where(u => u.PAC_RUT.Equals(MODEL_PACIENTE.PAC_RUT)).ToList();
if (PacLista.Count.Equals(0))
{
var strategy = _context.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
using (var transaction = _context.Database.BeginTransaction())
{
try
{
var imagenByte = await _lCargarImagen.ByteAvatarImageAsync(MODEL_PACIENTE.AvatarImage, _environment, "images/user_icon.png");
string TmpCodPac = _dataInput.PAC_COD_ODONT;
String vfCodPac = TmpCodPac.Substring(0, 4);
var Nuevo_Paciente = new MODELO_PACIENTE
{
PAC_CODIGO = _dataInput.PAC_CODIGO,
PAC_NOMBRE = _dataInput.PAC_NOMBRE.ToUpper(),
PAC_APELLIDO = _dataInput.PAC_APELLIDO.ToUpper(),
PAC_SEXO = _dataInput.PAC_SEXO,
PAC_RUT = _dataInput.PAC_RUT,
PAC_FECHA_NAC = _dataInput.PAC_FECHA_NAC,
PAC_EDAD = _dataInput.PAC_EDAD,
PAC_REPRESENTANTE = _dataInput.PAC_REPRESENTANTE?.ToUpper(),
PAC_DIRECCION = _dataInput.PAC_DIRECCION?.ToUpper(),
PAC_COMUNA = _dataInput.PAC_COMUNA?.ToUpper(),
PAC_OTRAS_COMUNAS = _dataInput.PAC_OTRAS_COMUNAS?.ToUpper(),
PAC_TELEFONO = _dataInput.PAC_TELEFONO,
PAC_CORREO = _dataInput.PAC_CORREO,
PAC_CONVENIO = _dataInput.PAC_CONVENIO?.ToUpper(),
PAC_PREVISIONES = _dataInput.PAC_PREVISIONES?.ToUpper(),
PAC_OBSERVACIONES = _dataInput.PAC_OBSERVACIONES?.ToUpper(),
PAC_COD_ODONT = vfCodPac,
PAC_IMAGEN = imagenByte,
PAC_FEC_REG = DateTime.Now,
PAC_FEC_ACT = DateTime.Now
};
await _context.AddAsync(Nuevo_Paciente);
_context.SaveChanges();
transaction.Commit();
_dataInput = null;
valor = true;
}
catch (Exception ex)
{
_dataInput.ErrorMessage = ex.Message;
transaction.Rollback();
valor = false;
}
}
});
}
else
{
_dataInput.ErrorMessage = $"El RUT {MODEL_PACIENTE.PAC_RUT} ya se encuentra Registrado";
// It should show this error in the respective "input", but the error message you see below in the image appears
}
}
else
{
foreach (var modelState in ModelState.Values)
{
foreach (var error in modelState.Errors)
{
_dataInput.ErrorMessage += error.ErrorMessage;
}
}
valor = false;
}
return valor;
}
If I debug, when I start it loads the 2 records from the dentist table, but when I put the existing ID at the time of appearing the error message appears what is seen in the image and when trying to load the list again it comes out null
After checking the ID error, the "Odontologia Lista" method returns null and the title error appears
where is the problem ?, I appreciate your help or guide to solve this problem.
You can try to check the following code:
MODEL_PACIENTE = new PACIENTE
{
PAC_CODIGO = TempCodPac,
//Genero_Lista = _lPacienteGen.GetGenero(_context),
Comuna_Lista = _lComuna.GetComuna(_context),
//Odontologo_Lista = _lOdontologo.GetOdontologo(_context),
PAC_COD_ODONT = "00000"
};
Odontologo_Lista = _lOdontologo.GetOdontologo(_context), is commented.If _dataInput == null && _DataPac1 == null && _DataPac2 == null,the Odontologo_Lista will not be set,and you will get the error Value cannot be null.
I am using this code for authorization on controllers.
with [Authorize(Policy = "CustomRole")]
The thing happened that after 3 or 4 request it fails with
A second operation started on this context before a previous operation completed
public class CustomRoleRequirement : AuthorizationHandler<CustomRoleRequirement>, IAuthorizationRequirement
{
public CMSContext _context = new CMSContext();
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomRoleRequirement requirement)
{
var routeobj = context.Resource as Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;
var c = routeobj.RouteData.Values.Values.ToList();
var keys = routeobj.RouteData.Values.Keys.ToList();
string area = "";
string id = "";
string controller = "";
string action = "";
string module = "";
foreach (var item in keys)
{
if (item=="area")
{
int indexs = keys.FindIndex(cc => cc == "area");
area = c[indexs].ToString();
}
else if (item == "id")
{
int indexs = keys.FindIndex(cc => cc == "id");
id = c[indexs].ToString();
}
else if (item == "controller")
{
int indexs = keys.FindIndex(cc => cc == "controller");
controller = c[indexs].ToString();
}
else if (item == "module")
{
int indexs = keys.FindIndex(cc => cc == "module");
module = c[indexs].ToString();
}
else if (item == "action")
{
int indexs = keys.FindIndex(cc => cc == "action");
action = c[indexs].ToString();
}
}
string modulelink = controller;
if (!string.IsNullOrEmpty(module))
{
modulelink = modulelink + "/" + module;
}
List<string> Roles = new List<string>();
int UserId = Auth.UserID;
string UserName = Auth.UserName;
if (UserName == "superadmin")
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
// apparently the error occurred here
var moduleobj = _context.AppModules.FirstOrDefault(q => q.Link == modulelink);
if (moduleobj != null)
{ // 69 role is assessing news module
//60 role is accessing page module
var RolesModulesobj = _context.AppRolesModules.FirstOrDefault(q => q.ModuleId == moduleobj.ModuleId && q.RolesId == Auth.RoleId);
if (RolesModulesobj != null)
{
string permissionsobj = RolesModulesobj.Permissions;
List<string> PermissionsListobj = permissionsobj.Split(',').Select(x => x.Trim()).ToList();
var FindFullAccess = PermissionsListobj.FirstOrDefault(q => q.Contains("FullAccess:true"));
if (FindFullAccess != null)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
var abc = PermissionsListobj.FirstOrDefault(q => q.Contains(action + ":true"));
if (abc != null)
{
context.Succeed(requirement);
return Task.CompletedTask;
}
else
{
context.Fail();
return Task.CompletedTask;
}
}
}
}
}
The error occurred at this line above
var moduleobj = _context.AppModules.FirstOrDefault(q => q.Link == modulelink);
How can I make task wait before the second operation started in the method above?
You can't use a singleton DB context. You either create one each time you need one or you pool them.
I cant figured out how perform sort in a details page. I have a classic page with list of order and for each row i have a actionlink to return details view of that order.
i try this
public ActionResult Details(int? anno,int? nr, string centro, string sortOrder)
{
ViewBag.Codice = String.IsNullOrEmpty(sortOrder) ? "Articolo_desc" : "";
if (anno == null && nr == null && string.IsNullOrEmpty(centro))
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
else
{
string s = "anno=" + Request.QueryString["anno"] + "&nr=" + Request.QueryString["nr"] + "¢ro=" + Request.QueryString["centro"];
ViewBag.search = s.Replace("search=", "").Replace("%3D", "=");
}
var righe = from d in db.DETAILS
where d.Anno == anno && d.Num == nr && d.Centro == centro
select new DetailsOrdersView
{
Articolo = r.Codice,
...
};
if (righe == null)
return HttpNotFound();
switch(sortOrder)
{
case "Articolo_desc":
righe = righe.OrderByDescending(i => i.Articolo);
break;
default:
righe = righe.OrderBy(i => i.Articolo);
break;
}
return View(righe);
}
}
and in details view
#Html.ActionLink("codice","Details", new { sortOrder = ViewBag.Codice, ViewBag.search })
but i on sorting I get bad request and this is the route
Orders/Details?sortOrder=Articolo_desc&search=anno%3D2017%26nr%3D6%26centro%3D1
#Html.ActionLink("codice", "Details", new { sortOrder = ViewBag.Codice, anno = ViewBag.Anno, centro = ViewBag.Centro , nr= ViewBag.Numero })
i solved as above
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?
I have applied search method in my project but , I have also Action index()
and getting erorr. (The current request for action 'Index' on controller type 'AdultLiteracyTeachersController' is ambiguous between the following action methods:)
public ViewResult Index(string searchstring, string currentFilter, int? page)
{
if (searchstring != null)
{
page = 1;
}
else
{
searchstring = currentFilter;
}
ViewBag.CurrentFilter = searchstring;
var teachers = from r in db.AdulLiteracyTeachers select r;
if (!string.IsNullOrEmpty(searchstring))
{
teachers = teachers.Where(r => r.ALTName.ToUpper().Contains(searchstring.ToUpper()));
}
teachers = teachers.OrderBy(r => r.ALTName);
int pagesize = 10;
int pageNo = (page ?? 1);
return View(teachers.ToPagedList(pageNo, pagesize));
}
The other ActionResult.index()
public ActionResult Index()
{
var adulliteracyteachers = db.AdulLiteracyTeachers.Include(a => a.District);
return View(adulliteracyteachers.ToList());
}
Action result is used for calling all data how can I aplly in single index ?
Combine them:
public ViewResult Index(string searchstring, string currentFilter, int? page)
{
if (searchString == null && currentFilter == null && !page.HasValue)
{
// No parameters
var adulliteracyteachers = db.AdulLiteracyTeachers.Include(a => a.District);
return View(adulliteracyteachers.ToList());
}
// Regular code here down
if (searchstring != null)
{
page = 1;
}
else
{
searchstring = currentFilter;
}
ViewBag.CurrentFilter = searchstring;
var teachers = from r in db.AdulLiteracyTeachers select r;
if (!string.IsNullOrEmpty(searchstring))
{
teachers = teachers.Where(r => r.ALTName.ToUpper().Contains(searchstring.ToUpper()));
}
teachers = teachers.OrderBy(r => r.ALTName);
int pagesize = 10;
int pageNo = (page ?? 1);
return View(teachers.ToPagedList(pageNo, pagesize));
}