Here i'm using Repo Class in that i wrote some Logic.When that Logic success I want to pass that string msg to mvc controller please Help me
Repo.cs
public void validateUser(Auth aut)
{
var xx=aut.Email;
var xr=db.Auths.Where(rr=>rr.Email == xx).FirstOrDefault();
if (xr != null)
{
var x = (from n in db.Auths
where n.Email == xr.Email && n.Password == xr.Password
select n).FirstOrDefault();
if (x != null)
{
var xz = (from n in db.Auths
where n.Email == xr.Email && n.Password == xr.Password && n.Active == aut.Active
select n).FirstOrDefault();
if (xz != null)
{
string Acc = "Your Account Activated....";
}
}
}
else
{string ddd = "Your Account not Activated....";}}
Controller.cs
Repo objrepo = new Repo();
public ActionResult Login(Auth aut)
{
if (ModelState.IsValid)
{
objrepo.validateUser(aut);
ViewBag.Success = "Success.....";
}
else
ViewBag.msg = "Invalid.....";
return View();
}
You could try this:
public string validateUser(Auth aut)
{
string result = "Invalid Email Address ....";
var xx=aut.Email;
var xr=db.Auths.Where(rr=>rr.Email == xx).FirstOrDefault();
if (xr != null)
{
result = "Invalid Password ....";
var x = (from n in db.Auths
where n.Email == xr.Email && n.Password == xr.Password
select n).FirstOrDefault();
if (x != null)
{
result = "Your Account is not Activated ....";
var xz = (from n in db.Auths
where n.Email == xr.Email && n.Password == xr.Password && n.Active == aut.Active
select n).FirstOrDefault();
if (xz != null)
{
result = "Your Account Activated....";
}
}
}
return result;
}
And this:
public ActionResult Login(Auth aut)
{
if (ModelState.IsValid)
{
string result = objrepo.validateUser(aut);
ViewBag.Success = result;
}
return View();
}
Change return type from void to string in validateUser method of repo.cs file.
Return message from method to controller.
i.e.
In controller file
public ActionResult Login(Auth aut)
{
if (ModelState.IsValid)
ViewBag.msg = objrepo.validateUser(aut);
else
ViewBag.msg = "Invalid.....";
return View();
}
Use ViewBag.msg in view file.
Thanks,
Hiral Shah
Related
hai im new on c# actually i have an issue with my code which i couldnt find the error. I making a controller which i can see the details that user sumbit. When im debug it say that " Use 'await' to ensure that any asynchronous operations". i try to put await every each of line but doesnt working.
plus in my cases i dont use for each method
here is my code :-
public async Task<ActionResult> Details(int id, string currentFilter)
{
try
{
BizRepMaster bizRepmaster = _bizRepMasterService.Find(id);
if (bizRepmaster.RepCountry != null)
ViewBag.BizCountry = _countryMasterService.Find(bizRepmaster.RepCountry).tCountry;
else
ViewBag.BizCountry = "";
if (bizRepmaster.RepState == null)
{
ViewBag.State = "";
}
else
{
if (bizRepmaster.RepState == "Oth")
{
ViewBag.State = "Others";
}
else
{
ViewBag.State = GetStateName(bizRepmaster.RepCountry, bizRepmaster.RepState);
}
}
if (bizRepmaster.MailState == null)
{
ViewBag.MailState = "";
}
else
{
if (bizRepmaster.RepState == "Oth")
{
ViewBag.MailState = "Others";
}
else
{
ViewBag.MailState = GetBizStateName(bizRepmaster.RepCountry, bizRepmaster.MailState);
}
}
ViewBag.AMNationality = _countryMasterService.GetCountryMaster()
.Where(a => a.tISO == bizRepmaster.RepNationality).Single().tCountry;
ViewBag.AMIdType = _idTypeService.GetIdTypes()
.Where(a => a.TypeID == bizRepmaster.RepIdType).Single().LabelName;
if (bizRepmaster.DialCode != null)
{
ViewBag.DialCode = _unitOfWorkAsync.Repository<Country>().Find(bizRepmaster.DialCode).tDialCode;
}
if (bizRepmaster.NatureOfBusiness != null)
{
}
ViewBag.AMResType = _unitOfWorkAsync.Repository<ResidencyType>().Find(bizRepmaster.RepResidencyType).LabelName;
ViewBag.AMJobType = _unitOfWorkAsync.Repository<SenderJobType>().Find(bizRepmaster.RepJobType).LabelName;
ViewBag.StateList = new SelectList(_stateService.GetStates(), "nId", "tStateDesc");
if (bizRepmaster.IdType != null)
ViewBag.IdTypeList = _idTypeService.Find(Convert.ToInt32(bizRepmaster.RepIdType)).LabelName;
ViewBag.CreatedUserName = _userProfileService.GetUserProfile().Where(a => a.UserID == Convert.ToInt32(bizRepmaster.CreatedBy)).Single().LoginId;
if (bizRepmaster.ApprovedBy != null)
{
ViewBag.ApprovedUserName = _userProfileService.GetUserProfile().Where(a => a.UserID == Convert.ToInt32(bizRepmaster.ApprovedBy)).Single().LoginId;
}
if (bizRepmaster.LastUpdatedBy != null)
{
ViewBag.LastUpdatedName = _userProfileService.GetUserProfile().Where(a => a.UserID == Convert.ToInt32(bizRepmaster.LastUpdatedBy)).Single().LoginId;
}
if (bizRepmaster.LastApprovedBy != null)
{
ViewBag.LastApprovedName = _userProfileService.GetUserProfile().Where(a => a.UserID == Convert.ToInt32(bizRepmaster.LastApprovedBy)).Single().LoginId;
}
ViewBag.SenderId1 = bizRepmaster.SenderId;
return View("_BizRepDetails", bizRepmaster);
}
catch (Exception ex)
{
return PartialView("_ErrorMessageView");
}
}
I am trying to get the point and solve problem with SelectListItem. As Admin I want to be able to assign Client to register User
public IActionResult Edit(string Id)
{
var user = _db.ApplicationUsers.FirstOrDefault(u => u.Id == Id);
if (user == null)
{
return NotFound();
}
var userRole = _db.UserRoles.ToList();
var roles = _db.Roles.ToList();
var client = _db.Clients.ToList();
var role = userRole.FirstOrDefault(u => u.UserId == user.Id);
if (role != null)
{
user.Role = roles.FirstOrDefault(u => u.Id == role.RoleId).Id;
}
if(client != null)
{
}
user.RoleList = _db.Roles.Select(u => new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem
{
Text = u.Name,
Value = u.Id
});
user.ClientList = _db.Clients.Select(u => new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem
{
Text = u.Name,
Value = u.Id.ToString()
});
return View(user);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(ApplicationUser user)
{
if (ModelState.IsValid)
{
var objFromDb = _db.ApplicationUsers.FirstOrDefault(u => u.Id == user.Id);
if (objFromDb == null)
{
return NotFound();
}
var userRole = _db.UserRoles.FirstOrDefault(u => u.UserId == objFromDb.Id);
if (userRole != null)
{
var previousRoleName = _db.Roles.Where(u => u.Id == userRole.RoleId).Select(e => e.Name).FirstOrDefault();
await _userManager.RemoveFromRoleAsync(objFromDb, previousRoleName);
}
await _userManager.AddToRoleAsync(objFromDb, _db.Roles.FirstOrDefault(u => u.Id == user.Role).Name);
objFromDb.Name = user.Name;
objFromDb.Email = user.Email;
objFromDb.PhoneNumber = user.PhoneNumber;
objFromDb.StreetAddress = user.StreetAddress;
objFromDb.City = user.City;
objFromDb.PostalCode = user.PostalCode;
objFromDb.RoleList = user.RoleList;
objFromDb.ClientList = user.ClientList;
_db.SaveChanges();
return RedirectToAction(nameof(Index));
}
user.RoleList = _db.Roles.Select(u => new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem
{
Text = u.Name,
Value = u.Id
});
user.ClientList = _db.Clients.Select(u => new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem
{
Text = u.Name,
Value = u.Id.ToString()
});
return View(user);
}
Somehow everything works fine only I can not change ClientList and I try to debug application but I can not see anything wrong.
I would be very thankfull If someone could check code and tell me where I made mistake ? What is wrong with this code, why my ClientList cannot be Edited
The error message tell me that ModelState is false and I notice error here
objFromDb.ClientList = user.ClientList;
And I change to
objFromDb.ClientId= user.ClientId;
And now it works ! :)
public ActionResult UploadImage(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
try
{
string path = Path.Combine(Server.MapPath("~/Images"),
Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.FileStatus = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.FileStatus = "ERROR:" + ex.Message.ToString();
}
}
else
{
ViewBag.FileStatus = "You have not specified a file.";
}
return Json("No files selected.", JsonRequestBehavior.AllowGet);
}
Second ActionResult PhysicianBiodata()
public ActionResult PhysicianBiodata (int? Id)
{
PhysicianBiodata newForm = new PhysicianBiodata();
if (Id <= 0 || Id == null)
{
return RedirectToAction("UploadImage", "ServiceCompendium",
{HttpPostedFileBase httpPostedFileBase});
}
else
{
newForm = compendiumData.GetPhysicianBiodatas().Where(x => x.ID == Id)
.FirstOrDefault();
}
return View(newForm);
}
and I want to call this UploadImage() into PhysicianBiodata() but its not working. Can you please help me....
Can you fix the last argument to the redirect?
Something like
return RedirectToAction("UploadImage", "ServiceCompendium", { new #file =httpPostedFileBase});
Also, where is httpPostedFileBase in the PhysicianBiodata method?
On login I am just assigning values to session but after login it becomes null. I set the session timeout as well but still it doesn't work.
public ActionResult Login([Bind(Include = "Username, Password")] LoginModel loginModel, string ReturnUrl)
{
if (ModelState.IsValid)
{
Egov_Users eGov_Users = db.Egov_Users
.Where(p => p.UserType.Type != "O" && p.UserName == loginModel.Username)
.FirstOrDefault();
if (eGov_Users == null)
{
ModelState.AddModelError("", "Invalid username");
return View();
}
else
{
if (eGov_Users.Password != loginModel.Password)
{
ModelState.AddModelError("", "Invalid Password");
return View();
}
var loginDetail = new LoginDetails();
loginDetail.supplierID = (eGov_Users.SupplierID != null) ? eGov_Users.SupplierID.Value : 0;
loginDetail.userID = eGov_Users.UserId;
loginDetail.username = eGov_Users.UserName;
loginDetail.firstName = eGov_Users.FirstName;
loginDetail.lastName = eGov_Users.LastName;
Session["UserID"] = loginDetail.userID;
Session["SupplierID"] = loginDetail.supplierID;
Session["Username"] = loginDetail.username;
Session["DisplayName"] = loginDetail.firstName + " " + loginDetail.lastName;
if (string.IsNullOrEmpty(ReturnUrl))
{
return RedirectToAction("Index", "Users");
}
}
}
return RedirectToAction("Login", "Login");
}
In webconfig I have set the session timeout as well.
This is my action method has been defined in Home controller for updating row
[HttpPost]
public ActionResult UpdateISRCEntry(ABC.Models.tbl1 z, List<string> verticall,string Album, string Song)
{
if (Session["user"] != null)
{
if (verticall != null)
{
foreach (string s1 in verticall)
{
if (s1 == "Radio")
{ z.Radio = "Radio"; }
if (s1 == "Online")
{ z.Online = "Online"; }
if (s1 == "Mobile")
{ z.Mobile = "Mobile"; }
}
}
tbl1.Service.Class1.updatetbl1(z, Album, Song);
return RedirectToAction("Home");
}
else
{
return RedirectToAction("Index");
}
}
and below is my method has been implemented in class1 to implement updatable row
public static bool updatetbl1(tbl1 obj, string Album, string Song)
{
ABC.Models.tbl1 objmain = new Models.mainISRC();
using (ABCManagementDBEntities1 dbcontect = new ABCManagementDBEntities1())
{
var zz = (from z in dbcontect.tbl1
where z.Album == Album && z.Song == Song select z
).SingleOrDefault();
objmain.Mood = obj.Mood;
objmain.Online = obj.Online;
objmain.Radio = obj.Radio;
dbcontect.SaveChanges();
return true;
}
return false;
}
All these codes are running successfully but the update is not reflected in my table for that row. However, during running my code no any kind of error is arise. Please help someone.
Add this before dbcontect.SaveChanges();
dbcontect.Entry(objmain).State = EntityState.Modified;
dbcontect.SaveChanges();
or I think just this will do
this.UpdateModel(objmain);
dbcontect.SaveChanges();
You should update entity before SaveChanges()
Why are you pulling the zz object and never use it? The way your wrote your "updatetbl1" method, you are inserting a new object (objmain) to the database instead of updating the zz object. Am I assuming correct here?
I think it should be like this:
public static bool updatetbl1(tbl1 obj, string Album, string Song)
{
ABC.Models.tbl1 objmain = new Models.mainISRC();
using (ABCManagementDBEntities1 dbcontect = new ABCManagementDBEntities1())
{
var zz = (from z in dbcontect.tbl1
where z.Album == Album && z.Song == Song select z
).SingleOrDefault();
zz.Mood = obj.Mood;
zz.Online = obj.Online;
zz.Radio = obj.Radio;
dbcontect.Entry(zz).State = EntityState.Modified;
dbcontect.SaveChanges();
return true;
}
return false;
}