I really need your help on this guys I am stuck and not sure where to start the fix. So i have this form where the user can select a case and parties. I am supposed save and pass along the values of the selected items. I was able to save the case selections but i am having trouble saving the selected party. Here is my code snippets regarding gathering data and saving them.
CONTROLLER:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
VisitEntryService:
public void Create(VisitEntry visitEntry,IList<Guid>caseIds, IList<Guid>partyIds )
{
EnsureValid(visitEntry);
_visitEntryRepository.Save(visitEntry);
caseIds = AddCurrentCaseToCases(visitEntry.CaseId, caseIds,partyIds);
foreach (var caseId in caseIds.Distinct())
{
var visit = new Visit {CaseId = caseId, VisitEntryId = visitEntry.VisitEntryId};
_visitService.Create(visit);
}
}
VisitEntryRepository:
public void Save(VisitEntry visitEntry)
{
if (visitEntry.VisitEntryId == Guid.Empty)
{
visitEntry.VisitEntryId = Guid.NewGuid();
visitEntry.DateCreated = DateTime.Now;
DataContext.VisitEntries.InsertOnSubmit(visitEntry);
}
else
{
var currentVisitEntry = Get(visitEntry.VisitEntryId);
if (currentVisitEntry == null) throw RepositoryExceptionFactory.Create("VisitEntry", "VisitEntryId");
currentVisitEntry.DateModified = DateTime.Now;
currentVisitEntry.VisitDate = visitEntry.VisitDate;
currentVisitEntry.VisitType =
DataContext.VisitTypes.SingleOrDefault(vt => vt.VisitTypeId == visitEntry.VisitTypeId);
currentVisitEntry.Note = visitEntry.Note;
}
DataContext.SubmitChanges();
}
I am not sure how to get this to save the selected party as it is saving the case information and selected case. Thanks for any feedback!
The save call is a bit earlier so your changes made after your fire SubmitChanges, move the SubmitChanges to the end you should good to go I believe
UPDATE
what I mean is change code like following and see if that helps
CONTROLLER:
[HttpPost]
[ValidateInput(false)]
public ActionResult Create(VisitViewModel viewModel, Guid[] associatedCasesSelected, Guid[] selectedParties)
{
if (!ModelState.IsValid)
{
viewModel.Time = _timeEntryHelper.Value;
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
var visitEntry = Mapper.Map<VisitViewModel, VisitEntry>(viewModel);
visitEntry.VisitDate = _timeEntryHelper.AddTimeToDate(visitEntry.VisitDate);
visitEntry.UserId = _currentUser.UserId;
visitEntry.OfficeId = _currentUser.OfficeId;
try
{
_visitEntryService.Create(visitEntry, associatedCasesSelected, selectedParties);
this.FlashInfo(string.Format(Message.ConfirmationMessageCreate, Resources.Entities.Visit.EntityName));
DataContext.SubmitChanges();
}
catch (RulesException ex)
{
ex.CopyTo(ModelState);
}
if (ModelState.IsValid)
return RedirectToAction("Edit", "Case", new { caseId = viewModel.CaseId });
AddLookupsToViewModel(viewModel);
return View(viewModel);
}
VisitEntryRepository:
public void Save(VisitEntry visitEntry)
{
if (visitEntry.VisitEntryId == Guid.Empty)
{
visitEntry.VisitEntryId = Guid.NewGuid();
visitEntry.DateCreated = DateTime.Now;
DataContext.VisitEntries.InsertOnSubmit(visitEntry);
}
else
{
var currentVisitEntry = Get(visitEntry.VisitEntryId);
if (currentVisitEntry == null) throw RepositoryExceptionFactory.Create("VisitEntry", "VisitEntryId");
currentVisitEntry.DateModified = DateTime.Now;
currentVisitEntry.VisitDate = visitEntry.VisitDate;
currentVisitEntry.VisitType =
DataContext.VisitTypes.SingleOrDefault(vt => vt.VisitTypeId == visitEntry.VisitTypeId);
currentVisitEntry.Note = visitEntry.Note;
}
}
Related
in this project i create cardGroup. in httpGet Method we get some needed info and pass to view to fill dropdown. when httpPost trigger if some field Date has Problem we must return error with addModelError but after return View, all ViewData Clear and Return Exception. how can handle this. just show error in view.
[HttpGet]
[Route("CreateCardGroup")]
public ActionResult CreateCardGroup()
{
var discounts =
UnitOfWork.DiscountPatternRepository.GetNotExpireDiscountPattern();
var discountDtos = discounts?.Select(c => new SelectListItem
{
Text = c.PatternTitle,
Value = c.Id.ToString()
}).ToList();
ViewData["DiscountPatterns"] = discountDtos;
var serials =
UnitOfWork.ChargeCardSerialRepository.GetNotAssignedSerials();
var serialDtos = serials?.Select(c => new SelectListItem
{
Text = c.SerialNumber.ToString(),
Value = c.Id.ToString()
}).ToList();
ViewData["ChargeSerials"] = serialDtos;
ViewData["CardSerialCount"] =
UnitOfWork.GiftCardSerialRepository.GetNotUsedGiftSerials();
return View();
}
[HttpPost]
[Route("CreateCardGroup")]
public ActionResult CreateCardGroup(CardGroupCreateDto dto)
{
if (!ModelState.IsValid)
return View(dto);
if(!UnitOfWork.DiscountPatternRepository
.IsCardGroupDateInRange(dto.DiscountPatternId,
dto.ActiveFromDate, dto.ActiveToDate))
{
ModelState.AddModelError("ActiveFromDate", #"Error In Date.");
return View(dto); <---Problem Here
}
var group = dto.LoadFrom();
var insertedId = UnitOfWork.CardGroupRepository.Add(group);
foreach (var rangeDto in group.CardGroupGiftSerialRanges)
{
for (var i = rangeDto.GiftCardSerialBegin; i <=
rangeDto.GiftCardSerialEnd; i++)
{
var serial =
UnitOfWork.GiftCardSerialRepository.GetBySerial(i);
if (serial != null)
{
serial.CardGroupGiftSerialRangeId = rangeDto.Id;
serial.DiscountPatternId = group.DiscountPatternId;
UnitOfWork.Complete();
}
}
}
return Redirect("/CardGroup");
}
From this article:
ViewData
ViewData is a property of ControllerBase class.
ViewData is used to pass data from controller to corresponding view
Its life lies only during the current request. If redirection occurs, then its value becomes null. It’s required typecasting for getting data and check for null values to avoid error.
So what's happening is once you've done your post back to the server, you're now in a different request, meaning, that you need to repopulate your ViewData items so that their values are populated again, or else they'll be null.
So I'd recommend refactoring your Dropdown population method into a private method on your controller and then call that method in your post when you find a validation error or are just returning by calling return View(dto).
If they're used in other controllers, you can add them to a LookupService or LookupRepository or even a general helpers class that contains your lookup logic (whatever fits into your UnitofWork pattern the best for you), to make them available to those other controllers, instead of having it as a private method as per my example.
So something like this for example:
[HttpGet]
[Route("CreateCardGroup")]
public ActionResult CreateCardGroup()
{
PopulateCreateCardGroupLookups();
return View();
}
[HttpPost]
[Route("CreateCardGroup")]
public ActionResult CreateCardGroup(CardGroupCreateDto dto)
{
if (!ModelState.IsValid)
{
PopulateCreateCardGroupLookups();
return View(dto);
}
if(!UnitOfWork.DiscountPatternRepository
.IsCardGroupDateInRange(dto.DiscountPatternId,
dto.ActiveFromDate, dto.ActiveToDate))
{
ModelState.AddModelError("ActiveFromDate", #"Error In Date.");
PopulateCreateCardGroupLookups();
return View(dto); <---Problem Here
}
var group = dto.LoadFrom();
var insertedId = UnitOfWork.CardGroupRepository.Add(group);
foreach (var rangeDto in group.CardGroupGiftSerialRanges)
{
for (var i = rangeDto.GiftCardSerialBegin; i <=
rangeDto.GiftCardSerialEnd; i++)
{
var serial =
UnitOfWork.GiftCardSerialRepository.GetBySerial(i);
if (serial != null)
{
serial.CardGroupGiftSerialRangeId = rangeDto.Id;
serial.DiscountPatternId = group.DiscountPatternId;
UnitOfWork.Complete();
}
}
}
return Redirect("/CardGroup");
}
private void PopulateCreateCardGroupLookups()
{
var discounts =
UnitOfWork.DiscountPatternRepository.GetNotExpireDiscountPattern();
var discountDtos = discounts?.Select(c => new SelectListItem
{
Text = c.PatternTitle,
Value = c.Id.ToString()
}).ToList();
ViewData["DiscountPatterns"] = discountDtos;
var serials =
UnitOfWork.ChargeCardSerialRepository.GetNotAssignedSerials();
var serialDtos = serials?.Select(c => new SelectListItem
{
Text = c.SerialNumber.ToString(),
Value = c.Id.ToString()
}).ToList();
ViewData["ChargeSerials"] = serialDtos;
ViewData["CardSerialCount"] =
UnitOfWork.GiftCardSerialRepository.GetNotUsedGiftSerials();
}
i have 2 actions .. one for User and i can add data to User table but for Order table my code didn't works and got catch error
this is my user code (Action in Controller)
[HttpPost]
public ActionResult Register(User user)
{
UserRepository blUser = new UserRepository();
if (ModelState.IsValid)
{
if (blUser.Add(user))
{
return Json(new JsonData() { Success = true });
}
else
{
return Json(new JsonData() { Success = false });
};
}
else
{
return Json(new JsonData() { Success = false });
}
}
and (UserRepository):
public class UserRepository : IDisposable
{
private HairCut.Models.MVCHairDresserDBEntities db = null;
public UserRepository()
{
db = new HairCut.Models.MVCHairDresserDBEntities();
}
public bool Add(HairCut.Models.User entity, bool autoSave = true)
{
try
{
db.Users.Add(entity);
if (autoSave)
return Convert.ToBoolean(db.SaveChanges());
else
return false;
}
catch
{
return false;
}
}
i just change User word to Order but when try to insert data to table i got catch and return false
Order code:
[HttpPost]
public ActionResult Reserve(int select, int user,int hdId)
{
Order order = new Order();
order.HairDresserId =hdId;
order.UserId = user;
order.timeCome = (select).ToString();
order.timeNow = DateTime.Now.ToString("dddh");
order.confirm = true;
OrderRepository blOrder = new OrderRepository();
if (blOrder.Add(order))
{
return Json(new JsonData() { Success = true });
}
else
{
return Json(new JsonData() { Success = false });
}
}
OrderRepository is similar UserRepository. so why cant insert ? where is my wrong ?
every time use breackpoint and debug my codes got catch in code return Convert.ToBoolean(db.SaveChanges());
OrderRepository have 2 foreignkey. when i checked entity quick watch, helper show me 2 extra field ( User and HairDresser with null value ) .. maybe i need set value to these ?
or maybe need create MetaData class to check validation like User values ( but i don't think this is my problem )
Hello i'm newbie to MVC,
i want to display webgrid in view,I'm trying to display create and display in same page,i'm getting problem at the time of displaying data in webgrid,
This is my code:
Controller:
[HttpPost]
public ActionResult Insert(Torder Model)
{
if(ModelState.IsValid)
{
try
{
ntity.Torders.Add(Model);
ntity.SaveChanges();
ModelState.Clear();
TempData["notice"] = "Successfully registered";
}
catch(Exception ex)
{
TempData["Failure"] = ex;
}
}
else
{
TempData["Failure"] = "Record Not Saved";
}
//var empoyees = Employee.GetList();
IEnumerable<Torder> model1 = GetProducts();
return View(model1);
}
public IEnumerable<Torder> GetProducts()
{
List<Torder> objStudent = new List<Torder>();
///*Create instance of entity model*/
/*Getting data from database for user validation*/
var _objuserdetail = (from data in ntity.Torders
select data);
foreach (var item in _objuserdetail)
{
objStudent.Add(new Torder { Cid = item.Cid, Ccustomername = item.Ccustomername, Citem = item.Citem, Corderamount = (int)item.Corderamount});
}
return objStudent;
}
Just pass your IEnumerable<Torder> like List<Torder> On page you can write foreach loop and create grid
--- Example:
public class Torder
{
public int Id {get;set;}
public string Name {get;set;}
}
[HttpPost]
public ActionResult Insert(Torder Model)
{
if(ModelState.IsValid)
{
try
{
ntity.Torders.Add(Model);
ntity.SaveChanges();
ModelState.Clear();
TempData["notice"] = "Successfully registered";
}
catch(Exception ex)
{
TempData["Failure"] = ex;
}
}
else
{
TempData["Failure"] = "Record Not Saved";
}
//var empoyees = Employee.GetList();
List<Torder> model1 = GetProducts();
return View(model1);
}
public List<Torder> GetProducts()
{
List<Torder> objStudent = new List<Torder>();
// your logic
return objStudent;
}
---------
Page:
-------------
//html code
#model List<Torder>
#foreach(Torder order in Model)
{
// here you can build you grid(table)
order.Name
order.Id
}
P.S In future I recommend write "clean" UI without Razor (Try learn Angular - it's really very good framework) –
It's hard to tell from code in comments, but you might just be missing the #grid.GetHtml()
The block you've shown defines the grid, but now you need to emit the HTML so something shows on the page. Put this after your #{} block right before the closing div tag.
Hi I'm trying to call the Get method in my CategoryController from my WareController. How would I do that.
I've tried this in my WareController
// GET: api/Ware?category=5
public List<WareDTO> GetByCategroy(int id)
{
BLLServiceGateway<List<WareDTO>> gate = new BLLServiceGateway<List<WareDTO>>();
var item = gate.Get(path + "?category=" + id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return item;
}
public IHttpActionResult ViewItems(int id)
{
var model = new WareModel()
{
wares = GetByCategroy(id),
currentCategory = Redirect("api/category/" + id) /// This is were I want to get the category object
};
}
return Ok(model);
and my CategoryController looks like this
// GET: api/Categories/5
public CategoryDTO Get(int id)
{
BLLServiceGateway<CategoryDTO> gate = new BLLServiceGateway<CategoryDTO>();
var item = gate.Get(path + id);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return item;
}
API controller are just classes, so you easily can do this:
currentCategory = new CategoryController().Get(id);
But there may me problems if you want to deal with context.
I have got following code and I have no clue which proper Unit Test I have write out for those methods and how it can be done. Basically I would like to use NUnit.Framework.
Thank you in advance for ANY clue!
[AllowAnonymous]
public ActionResult ForgotPassword(string id)
{
var model = new ForgotPasswordViewModel();
if (!string.IsNullOrEmpty(id))
{
#region Process Reset Password Key
try
{
var forgotPasswordEvent = AppModel.ForgotPasswordEvents.SingleOrDefault(x => x.UIDHash == id);
if (forgotPasswordEvent != null)
{
var stringToHash = string.Format("{0}---{1}---{2}", forgotPasswordEvent.UID.ToString(),
forgotPasswordEvent.UserId.ToString(), forgotPasswordEvent.Created.ToString());
var readyHash = SecurityHelper.GetHashString(stringToHash);
if (id == readyHash)
{
var forgotPasswordEventUserId = forgotPasswordEvent.UserId.ToString();
var realUser = AppModel.AspNetUsers.SingleOrDefault(x => x.Id == forgotPasswordEventUserId);
if (realUser != null)
{
var resetPasswordViewModel = new ResetPasswordViewModel();
resetPasswordViewModel.ResetPasswordData = id;
resetPasswordViewModel.UserName = realUser.UserName;
return RedirectToAction("ResetPassword", "Account", resetPasswordViewModel); // ResetPassword(resetPasswordViewModel);
}
}
}
else
{
return RedirectToAction("Index", "Home");
}
}
catch (Exception)
{
}
#endregion
}
#region Check if the user is logged in and fill out fileds for him.
var sessionManager = SessionWrapper.GetFromSession<SessionManager>("_SessionManager");
if (sessionManager != null)
{
var clientId = sessionManager.AppUser.ClientId;
if (clientId != null)
{
model.Email = sessionManager.AppUser.EmailID;
model.UserName = sessionManager.AppUser.UserName;
model.IsLoggedInUser = true;
}
}
#endregion
return View(model);
}
[HttpPost]
[AllowAnonymous]
public ActionResult ForgotPassword(ForgotPasswordViewModel model, FormCollection formCollection)
{
if (ModelState.IsValid)
{
try
{
#region Check user input
var user = AppModel.AspNetUsers.SingleOrDefault(x => x.UserName == model.UserName);
var areErrors = false;
if (user == null)
{
ModelState.AddModelError("UserDoesnotExist", DLMModelEntities.Properties.Resource.UserDoesNotExist);
areErrors = true;
}
if (user.EmailID != model.Email)
{
ModelState.AddModelError("EmailIsWrong", DLMModelEntities.Properties.Resource.EmailIsWrong);
areErrors = true;
}
if (areErrors)
return View(model);
#endregion
#region Send Email and inform user
try
{
var forgotPasswordEvent = new ForgotPasswordEvent();
var resetPasswordEmailUserState = new ResetPasswordEmailUserState();
resetPasswordEmailUserState.ForgotPasswordEventId = Guid.NewGuid();
resetPasswordEmailUserState.UserId = Guid.Parse(user.Id);
resetPasswordEmailUserState.Created = DateTime.Now;
forgotPasswordEvent.UID = resetPasswordEmailUserState.ForgotPasswordEventId;
forgotPasswordEvent.UserId = resetPasswordEmailUserState.UserId;
forgotPasswordEvent.IsSent = false;
forgotPasswordEvent.Created = resetPasswordEmailUserState.Created;
var stringToHash = string.Format("{0}---{1}---{2}", resetPasswordEmailUserState.ForgotPasswordEventId.ToString(),
resetPasswordEmailUserState.UserId.ToString(), resetPasswordEmailUserState.Created.ToString());
forgotPasswordEvent.UIDHash = SecurityHelper.GetHashString(stringToHash);
AppModel.ForgotPasswordEvents.Add(forgotPasswordEvent);
AppModel.SaveChanges();
var smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
// Set the MailerModel properties that will be passed to the MvcMailer object.
var m = new MailerModel();
m.UserName = user.UserName;
m.ResetPasswordLink = string.Format("{0}/{1}", Request.Url.AbsoluteUri, forgotPasswordEvent.UIDHash);
m.FromEmail = smtp.From;
m.Subject = AppConfiguration.ResetEmailSubject;
m.ToEmail = model.Email;
var client = new SmtpClientWrapper();
client.SendCompleted += (sender, e) =>
{
if (e.Error != null || e.Cancelled)
{
// Handle Error
}
else
{
try
{
var forgotPasswordEventsToUpdate = AppModel.ForgotPasswordEvents.SingleOrDefault(x => x.UID == resetPasswordEmailUserState.ForgotPasswordEventId);
if (forgotPasswordEventsToUpdate != null)
{
forgotPasswordEventsToUpdate.IsSent = true;
AppModel.SaveChanges();
}
}
catch (Exception ex)
{
ModelState.AddModelError("EmailEx", ex.Message);
}
}
};
Mailer.PasswordReset(m).SendAsync(resetPasswordEmailUserState, client);
model.IsResetEMailSent = true;
}
catch (Exception ex)
{
ModelState.AddModelError("EmailEx", ex.Message);
}
#endregion
}
catch (Exception ex)
{
ModelState.AddModelError("EmailEx", ex.Message);
}
}
return View(model);
}
As your code looks ltl messed up with more than one responsibility.
For Starter what you can do here is:
Refactor your code into small code snippets and move those dependencies into another classes.
when you will be done with first step you will be able to mock those classes using MOQ or NMock or another framework.
Let me know if you have any doubt in above points.