First, sorry for my bad English. I am from Brazil. And I am a beginner in .NET MVC5.
I had a model class Task
with ID
plus 4 editable columns. When creating a new Task
, the user must fill out only 2 of them (TaskType
and Subject
). The remaining two columns (UserID
and CreationDate
) must be populated with information obtained from the system: user ID and current date.
Then, in the Create
Get, I put this two information in the ViewBag:
public ActionResult Create()
{
ViewBag.TaskTypeID = new DAO.TaskTypesDAO().ListOfTypes();
ViewBag.ApplicationUserId = User.Identity.GetUserId();
ViewBag.CreationDate = DateTime.Now;
return View();
}
And in View Create I tried to include this information first, without showing it:
First, I tried HiddenFor()
and after with DisplayFor()
@Html.LabelFor(model => model.CreationDate, "Creation Date")
@Html.DisplayFor(model => model.CreationDate)
@Html.HiddenFor(model => model.CreationDate)
@Html.LabelFor(model => model.ApplicationUserId, "Creator")
@Html.DisplayFor(model => model.User.Id)
@Html.HiddenFor(model => model.ApplicationUserId)
DisplayFor()
doesn't show anything.
And when I submit the Post Create
method
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,TaskTypeID,Subject,CreationDate,ApplicationUserId")] Task task)
{
if (ModelState.IsValid)
{
db.Tasks.Add(task);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.TaskTypeID = new DAO.TaskTypesDAO().ListOfTypes();
ViewBag.ApplicationUserId = User.Identity.GetUserId();
ViewBag.CreationDate = DateTime.Now;
return View(tarefa);
}
The ModelState is invalid and task.CreationDate and task.ApplicationUserId are empty.
How can include this two information before the create post bind????
or else, How can include after and revalidate ModelState??
or .....