I am trying to set DateTime Field to display current time and date.
public DateTime Date { get; set; }
What I try so far to pass in setter Date.Now but doesn't work.
I am asking because I need to display DateTime.Now in View but this items should be hidden from User.
User can only see DateTime but can not Edit.
Also in Controller I use something like but doesn't work
DateTime Date = DateTime.Now;
Any idea where I made mistake and how to fix this issues ?
UPDATE
Here is my Controller
public NotesController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
IEnumerable<Notes> notes = _db.Notes.Include(u => u.Patient);
return View(notes);
}
//Upsert GET
public IActionResult Upsert(int? Id)
{
DateTime Date = DateTime.Now;
NotesVM notesVM = new NotesVM()
{
Notes = new Notes(),
PatientSelectList = _db.Patients.Select(i => new SelectListItem
{
Text = i.FirstName + i.LastName,
Value = i.Id.ToString()
})
};
Notes notes = new Notes();
if (Id == null)
{
// this is for create
return View(notesVM);
}
else
{
// this is for edit
notesVM.Notes = _db.Notes.Find(Id);
if (notesVM.Notes == null)
{
return NotFound();
}
return View(notesVM);
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Upsert(NotesVM notesVM)
{
if (ModelState.IsValid)
{
if (notesVM.Notes.Id == 0)
{
//Creating
_db.Notes.Add(notesVM.Notes);
}
else
{
//Updating
_db.Notes.Update(notesVM.Notes);
}
_db.SaveChanges();
return RedirectToAction("Index");
}
notesVM.PatientSelectList = _db.Patients.Select(i => new SelectListItem
{
Text = i.FirstName + i.LastName,
Value = i.Id.ToString()
});
return View(notesVM);
}
If you have a constructor for your controller you can set the date property like this:
public NotesController(ApplicationDbContext db)
{
_db = db;
Date = DateTime.Now;
}
updated my answer now that i have seen your constructor.
Related
I have a controller method that fails on the return statement
[HttpGet("{id}")]
public UserModel Get(int id)
{
System.Threading.Thread.CurrentThread.CurrentCulture =
new System.Globalization.CultureInfo("en-CA");
System.Threading.Thread.CurrentThread.CurrentUICulture =
new System.Globalization.CultureInfo("en-CA");
BP.DataAccess.DataUtilities.DatabaseCommand.ConnectionString =
_configuration["connectionStrings:PrimaryConnection"];
UserModel user = UserService.GetUserById(id);
return user;
}
The UserModel class has:
public int RoleTypeId { get; set; }
private ListModels.RoleTypeModel _RoleType;
public ListModels.RoleTypeModel RoleType
{
get
{
_RoleType = Trisura.BP.Core.ListServices
.RoleTypeService.GetRoleTypeById(RoleTypeId);
return _RoleType;
}
private set { _RoleType = value; }
}
public static RoleTypeModel GetRoleTypeById(int id)
{
int cultureId = CultureService.GetThreadCultureId();
List<ListModels.RoleTypeModel> localizedList =
GetRoleTypesLocalizedList(cultureId);
ListModels.RoleTypeModel roleTypeModel =
localizedList.Where(roletype => roletype.Id == id).FirstOrDefault();
if (roleTypeModel == null)
{
throw new CoreExceptions.ObjectNotFoundInDatabaseException(
string.Format("The requested role type (ID = {0}) was not found.", id));
}
return roleTypeModel;
}
public static RoleTypeModel GetRoleTypeById(int id)
{
// this returns "en-US" (0) instead of "en-CA" (1)
int cultureId = CultureService.GetThreadCultureId();
List<ListModels.RoleTypeModel> localizedList = GetRoleTypesLocalizedList(cultureId);
ListModels.RoleTypeModel roleTypeModel =
localizedList.Where(roletype => roletype.Id == id).FirstOrDefault();
if (roleTypeModel == null)
{
throw new CoreExceptions.ObjectNotFoundInDatabaseException(
string.Format("The requested role type (ID = {0}) was not found.", id));
return roleTypeModel;
}
}
when the controller hits return user;, it fails because the thread CurrentCulture is set to en-US even I explicitly said that culture is en-CA.
Does anyone have an explanation? Does this happen in a separate thread?
How to ensure that my model will run with the same culture?
How can I automatically add a date to my database in MVC? I don't know how to get the time from my computer without manually writing it in line c.Date = ;. My controller:
public ActionResult Add(Contact c)
{
bool Status = false;
string message = "";
if (ModelState.IsValid)
{
c.Date = DateTime;
db.Contact.Add(c);
db.SaveChanges();
Status = true;
}
else
{
message = "Invalid Request";
}
ViewBag.Message = message;
ViewBag.Status = Status;
return View(c);
}
Just simply use DateTime class.
c.Date = DateTime.Now;
Regarding the format, you can check this site: C# DateTime Format
You need to use the DateTime.Now property, also don't forget you can easily format the DateTime.Now with additional functions like DateTime.Now.ToLongDateString(). I've added it in your code:
public ActionResult Add(Contact c)
{
bool Status = false;
string message = "";
if (ModelState.IsValid)
{
c.Date = DateTime.Now;
db.Contact.Add(c);
db.SaveChanges();
Status = true;
}
else
{
message = "Invalid Request";
}
ViewBag.Message = message;
ViewBag.Status = Status;
return View(c);
}
I'm losing data during transfer from one action to another
What's wrong? I'm doing this:
public ActionResult Index(CV model)
{
return View();
}
public ActionResult rr()
{
CV _cv = new CV();
_cv.education = new List<Education>();
_cv.education.Add(new Education()
{
Faculty = "sa",
OnGoing = false,
Specialization = "asdasd",
UniversityName = "sulxan",
EndDate = DateTime.Now.AddDays(1),
StartDate = DateTime.Now
});
return RedirectToAction("Index", _cv);
}
And when I'm debugging to Index parameter model.education.count = 0 instead of 1. In rr action it's 1 with desired values.
My model class is:
public class CV
{
public List<Education> education { get; set; }
public Education newEducation { get; set; }
}
public class Education
{
public string UniversityName { get; set; }
public string Faculty { get; set; }
public string Specialization { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public bool OnGoing { get; set; }
}
Posting an answer because I'm too much of a noob to comment.
What Stephen Muecke said in his comment is totally correct - and, it's definitely important to persist your data. One other thing to note is that, based on the code you posted, you don't need the RedirectToAction if all you are trying to do is return the model with the view you want:
return View("Index", _cv);
Of course, without seeing how the rest of your app is built, that could potentially cause an issue.
You can use tempdata to store the entity and retrieve the data.use this code
public ActionResult Index()
{
CV model = (CV)TempData["cv"];
return View();
}
public ActionResult rr()
{
CV _cv = new CV();
_cv.education = new List<Education>();
_cv.education.Add(new Education()
{
Faculty = "sa",
OnGoing = false,
Specialization = "asdasd",
UniversityName = "sulxan",
EndDate = DateTime.Now.AddDays(1),
StartDate = DateTime.Now
});
TempData["cv"] = _cv;
return RedirectToAction("Index");
}
You can use tempdata
like this
public ActionResult Index()
{
var model = TempData["CV "] as CV;
return View();
}
public ActionResult rr()
{
CV _cv = new CV();
_cv.education = new List<Education>();
_cv.education.Add(new Education()
{
Faculty = "sa",
OnGoing = false,
Specialization = "asdasd",
UniversityName = "sulxan",
EndDate = DateTime.Now.AddDays(1),
StartDate = DateTime.Now
});
TempData["CV"] = _cv;
return RedirectToAction("Index");
}
Having trouble update users in AD
My Model:
public class UserModel
{
....
[ScaffoldColumn(false)]
[DisplayName("Fødselsdag")]
[DataType(DataType.Date)]
[NotMapped]
public DateTime extensionAttribute1_date
{
get
{
try
{
return DateTime.Parse(extensionAttribute1);
}
catch (Exception e)
{
return new DateTime();
}
}
set { }
}
}
My Controller:
[HttpPost]
public ActionResult Edit(string sAMAccountName, FormCollection collection, UserModel data)
{
if (ModelState.IsValid)
{
var config = new LdapConfiguration();
config.ConfigureFactory("domain.local").AuthenticateAs(new NetworkCredential("xxxx", "xxxxx"));
using (var context = new DirectoryContext(config))
{
var user = context.Query(new UserModel(), "OU=users,OU=xxx,DC=xxx,DC=dk", "User").FirstOrDefault(d => d.sAMAccountName == sAMAccountName);
if (user == null) return RedirectToAction("Index");
user.title = data.title;
user.mobile = data.mobile;
user.homePhone = data.homePhone;
user.streetAddress = data.streetAddress;
user.postalCode = data.postalCode;
user.l = data.l;
user.department = data.department;
user.physicalDeliveryOfficeName = data.physicalDeliveryOfficeName;
user.extensionAttribute1 = data.extensionAttribute1_date.ToLongDateString();
context.Update(user);
}
return RedirectToAction("Index");
}
return View();
}
When i submit to Edit Action i results in an error:
The requested attribute does not exist.
If i remove extensionAttribute1_date from the model i updates fine.
How do i exclude my calculated attributes from the update?
I have other attributes in the model such as Age which is calculated! Is this the wrong procedure for this?
/Michael
I have this method which passes in parameters and all the parameters hold a value but when i assign them to my viewModel one of them becomes null and not sure why:
[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;
viewModel.AssociatedCasesSelected = associatedCasesSelected;
viewModel.PartiesSelected = selectedParties;
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);
}
This is the line:
viewModel.PartiesSelected = selectedParties;
selectedParties should hold one value but when i assign it to partiesSelected - it shows me while debugging that PartiesSelected = null;
This is partiesSelected in my viewModel:
public IList<Guid> PartiesSelected { get; set; }