i am saving data through Model. SaveChanges not saving new record in database.
and not throwing any exception. kindly help anyone to get me out this situation.
[HttpPost]
public ActionResult SaveAmbulanceLocation1(Ambulance_Position AMmodel)
{
db.Configuration.ProxyCreationEnabled = false;
// var m = db.Ambulance_Position.FirstOrDefault(x => x.A_unique_ID == AMmodel.A_unique_ID);
try
{
if (ModelState.IsValid)
{
AMmodel.Date_Time = System.DateTime.Now;
db.Ambulance_Position.Add(AMmodel);
db.SaveChanges();
}
}
catch (Exception e )
{
}
return Json("saved", JsonRequestBehavior.AllowGet);
}
I would suggest making changes to your ActionMethod as shown below; basis this accepted Stackoverflow answer.
Note that this example is not tested though; and I might be wrong...
[HttpPost]
public ActionResult SaveAmbulanceLocation1(Ambulance_Position AMmodel)
{
db.Configuration.ProxyCreationEnabled = false;
Ambulance_Position ambulance_position = new Ambulance_Position();
ambulance_position = AMmodel;
// var m = db.Ambulance_Position.FirstOrDefault(x => x.A_unique_ID == AMmodel.A_unique_ID);
try
{
if (ModelState.IsValid)
{
//AMmodel.Date_Time = System.DateTime.Now;
ambulance_position.Date_Time = System.DateTime.Now;
db.Ambulance_Position.Add(ambulance_position);
db.SaveChanges();
}
}
catch (Exception e)
{
}
return Json("saved", JsonRequestBehavior.AllowGet);
}
Related
After saving my data to database I want to display the information entered by the user in another page (printRegInfo.cshtml). How can I do that?
public ActionResult Create(FirmServiceRegistrationViewModel firmServiceReg)
{
try
{
ViewBag.ServiceId = new SelectList(db.ServicesModels, "ServiceId", "ServiceName");
if (ModelState.IsValid)
{
FirmsModel frm_ = new FirmsModel();
frm_.Name = firmServiceReg.Name;
frm_.PropName = firmServiceReg.PropName;
frm_.Address = firmServiceReg.Address;
db.FirmsModels.Add(frm_);
db.SaveChanges();
int frmId = frm_.FirmId;
FirmServiceRegistrationModel frmServReg = new FirmServiceRegistrationModel();
frmServReg.ServiceId_ = firmServiceReg.ServiceId;
frmServReg.FirmId_ = frmId;
db.FirmServiceRegistrationModels.Add(frmServReg);
db.SaveChanges();
}
return View();
}
catch (Exception)
{
throw;
}
}
Now on successful insert of data I want to pass the data entered by the user [Name, PropName, Address] to the view page say printRegInfo.cshtml. How can I do that?
The below code just get entered info and carried to another page using temp data. Hence you need to cast the as per model data and populate in view.
public ActionResult Create(FirmServiceRegistrationViewModel firmServiceReg)
{
try
{
ViewBag.ServiceId = new SelectList(db.ServicesModels, "ServiceId", "ServiceName");
if (ModelState.IsValid)
{
FirmsModel frm_ = new FirmsModel();
frm_.Name = firmServiceReg.Name;
frm_.PropName = firmServiceReg.PropName;
frm_.Address = firmServiceReg.Address;
db.FirmsModels.Add(frm_);
db.SaveChanges();
int frmId = frm_.FirmId;
FirmServiceRegistrationModel frmServReg = new FirmServiceRegistrationModel();
frmServReg.ServiceId_ = firmServiceReg.ServiceId;
frmServReg.FirmId_ = frmId;
db.FirmServiceRegistrationModels.Add(frmServReg);
db.SaveChanges();
TempData["FirmRegData"]=frm_;
}
return RedirectToAction("printRegInfo","ControllerName");
}
catch (Exception)
{
throw;
}
}
public ActionResult printRegInfo()
{
try
{
FirmsModel frm_ =(FirmsModel)TempData["FirmRegData"];
// Here you will get all entered info.
}
return view(frm_);
}
catch (Exception)
{
throw;
}
}
Authorization Set
services.AddAuthorization(options =>
{
options.AddPolicy("MustNutritionist", policy =>
policy.RequireClaim("nutritionistId"));
});
Controller
NutritionistUpdateModel have id field.
[Authorize(Policy = "MustNutritionist")]
public BaseResponseModel PostEdit([FromForm] NutritionistUpdateModel nutritionistUpdateModel)
{
try
{
var result = nutritionistService.EditNutritionist(nutritionistUpdateModel);
if (result)
{
return new SuccessResponseModel<bool>(result);
}
else
{
return new BaseResponseModel(ReadOnlyValues.NutritionistNotFound);
}
}
catch (Exception ex)
{
return new BaseResponseModel(ex.Message);
}
}
Token Generation Claim
claims.Add(new Claim("nutritionistId", nutritionistId.ToString()));
Problem
I want to check equation of NutritionistUpdateModel.Id and Claims.nutritionistId. I can check with below code.But i must write lots of if else statement.Is there any easy way ?
private bool ChechNutritionistAuthorize(int nutritionistId)
{
var currentUser = HttpContext.User;
var nutritionistIdClaim=Int32.Parse(currentUser.Claims.FirstOrDefault(c => c.Type == "NutritionistId").Value);
if (nutritionistIdClaim == nutritionistId)
{
return true;
}
else
{
return false;
}
}
Using extension method like this
public static class IdentityExtensions
{
public static bool ValidateNutritionistId(this ClaimsPrincipal principal, int nutritionistId)
{
if (principal == null)
throw new ArgumentNullException(nameof(principal));
int.TryParse(principal.Claims.FirstOrDefault(c => c.Type == "NutritionistId").Value, out int nutritionistIdClaim);
return nutritionistIdClaim == nutritionistId;
}
}
and you can use like this
HttpContext.User.ValidateNutritionistId(your id here )
and you also need to add using statement and reuse same method in all of your Controllers
[HttpPost]
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
return View(user);
}
}
I keep on getting an error while saving data to the database.
UpdateDetail worked while retrieving message, but i keep getting error when saving.
Your issue is if your ModelState.IsValid == false, then you are not returning anything. I put a comment in code below where it is.
Depending on what your logic needs to do, would determine what needs to be returned if IsValid == false
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
// this is your issue, this needs to be outisde the if statement, or you have to do an else and return null (or whatever you need to based off your logic)
return View(user);
}
}
Keep return statement outside of If statement. this would fix your error.If model is valid model updated with user details from database will be pushed to View. other wise same user model will be pushed to the view.
[HttpPost]
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
}
return View(user);
}
I am using asp.net core RoleManager to perform roleClaim(permission) based authorization. The below code work fine but it take too much time execute because i delete the roleclaim each at a time. but i want to delete roleclaims(permission) at one shot delete query , Can anyone help me ? thank's in advance.
//my controller code
public async Task<IActionResult> SaveRolePermission([FromBody] RoleClaimVM model)
{
try
{
if (string.IsNullOrEmpty(model.RoleId) || model.ClaimValues.Length <= 0) return Json(new { status = false });
var role = await _roleManager.FindByIdAsync(model.RoleId);
if (role == null) return null;
var roleClaims = _roleManager.GetClaimsAsync(role).Result.ToList();
if (roleClaims.Any())
{
foreach (var item in roleClaims)
{
await _roleManager.RemoveClaimAsync(role, item);
}
}
foreach (var item in model.ClaimValues)
{
await _roleManager.AddClaimAsync(role, new Claim(CustomClaimtypes.Permission, item.ToLower()));
}
return Json(new { status = true });
}
catch (Exception)
{
return Json(new { status = false });
}
}
I'm trying to edit an article in my asp.net mvc project. This is what I do when I create a project:
public ActionResult Create(ArticleViewModel model)
{
if (ModelState.IsValid)
{
try
{
// Get the userID who created the article
User usr = userrepo.FindByUsername(User.Identity.Name);
model.UsernameID = usr.user_id;
repository.AddArticle(model.Title, model.Description, model.ArticleBody);
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}
return RedirectToAction("Index");
}
return View(model);
}
In my repository:
public void AddArticle(string Title, string Description, string ArticleBody)
{
item Item = new item()
{
item_title = Title,
item_description = Description,
article_body = ArticleBody,
item_createddate = DateTime.Now,
item_approved = false,
user_id = 1,
district_id = 2,
link = "",
type = GetType("Article")
};
try
{
AddItem(Item);
}
catch (ArgumentException ae)
{
throw ae;
}
catch (Exception)
{
throw new ArgumentException("The authentication provider returned an error. Please verify your entry and try again. " +
"If the problem persists, please contact your system administrator.");
}
Save();
// Immediately persist the User data
}
public void AddItem(item item)
{
entities.items.Add(item);
}
But now I want to edit an article, this is what I have till now:
public ActionResult Edit(int id)
{
var model = repository.GetArticleDetails(id);
return View(model.ToList());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(ArticleViewModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the User
try
{
item Item = repository.GetArticleDetailsByTitle(model.Title);
Item.item_title = model.Title;
Item.item_description = model.Description;
Item.article_body = model.ArticleBody.
// HERE I NEED TO SAVE THE NEW DATA
return RedirectToAction("Index", "Home");
}
catch (ArgumentException ae)
{
ModelState.AddModelError("", ae.Message);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
As you can see I check the adjusted text and drop it in "Item". But how can I save this in my database? (the function in my repository)
I think your save() method had entityobject.SaveChanches()
So you want to call that save() method in here
try
{
item Item = repository.GetArticleDetailsByTitle(model.Title);
Item.item_title = model.Title;
Item.item_description = model.Description;
Item.article_body = model.ArticleBody.
**Save();**
return RedirectToAction("Index", "Home");
}
should be need to only Save() method, could not need to AddItem() method .
I'm afraid you'll need to get article again from database, update it and save changes. Entity framework automatically tracks changes to entites so in your repository should be:
public void EditArticle(Item article)
{
var dbArticle = entities.items.FirstOrDefault(x => x.Id == article.Id);
dbArticle.item_title = article.item_title;
//and so on
//this is what you call at the end
entities.SaveChanges();
}