Question

Good Morning, Evening or night

I was wondering how I can add a value to an existing key in ModelState. Here is what I have done yet:

[HttpPost]
    public ActionResult Create(VM_RoleGroup vm_roleGroup)
    {
        RoleGroup roleGroups = Mapper.Map<VM_RoleGroup, MAHAL_E_MA_Model.POCO.RoleGroup>(vm_roleGroup);
        roleGroups.ModifiedDate = UtilityHands.GeneralTools.ConvertToShamsi(DateTime.Now);
        roleGroups.Description = vm_roleGroup.Description ?? MAHAL_E_MA_Proj.ApplicationResources.GeneralResource.NoDescription;

        **if (ModelState.ContainsKey("ModifiedDate") && ModelState["ModifiedDate"].Value == null)
        {
            ModelState["ModifiedDate"].Value = new ValueProviderResult("", roleGroups.ModifiedDate, CultureInfo.CurrentUICulture);    
        }
        else if (!ModelState.ContainsKey("ModifiedDate"))
        {
            ModelState.Add("ModifiedDate", new ModelState { Value = new ValueProviderResult("", roleGroups.ModifiedDate, CultureInfo.CurrentUICulture) });
        }**

        if (ModelState.IsValid)
        {
            unitOfWork.RoleGroupRepository.InsertData(roleGroups);
            unitOfWork.RoleGroupRepository.Save();
            return RedirectToAction("Index");
        }

        return View(vm_roleGroup);
    }

But the ModelState is still invalid since it lacks the Value of a key named 'ModifiedDate'. Remember that, the value is not set on the client side by the user. It needs to be set programmatically. By the way, The 'ModifiedDate' is a required field in the database.

Any ideas pleas? Thanks in advance

Was it helpful?

Solution

you should pass the ModifiedDate through as part of the viewmodel, and then just overwrite it to DateTime.Today in the controller.

ie. prepopulate it the view

@Html.Hidden(Model.ModifiedDate,DateTime.Today);

and since this isn'tsecure, overwrite it in the controller

roleGroups.ModifiedDate = DateTime.Today;

or if its a universal field across your entire application (on all models), you can actually add custom code to do this in the mapper, but I'm unsure of the circumstances.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top