1 Replies - 527 Views - Last Post: 16 October 2016 - 10:25 AM

#1 Coding in the name of  Icon User is offline

  • D.I.C Regular

Reputation: 67
  • View blog
  • Posts: 291
  • Joined: 07-July 10

Hidden field has wrong value

Posted 15 October 2016 - 09:59 AM

I have a typical get/post set of actions for adding a new model to the database. I'm trying to add an intermediate step that will ask for confirmation from the user if an object with some of the same values already exists in the database.

I've added this piece to the view inside a form tag. When the get method is called ViewBag.JobAlreadyExists is false, so a Confirmed field is added to the form with a value of False. When the model is posted this flag makes the method check for existing models with the same values. If it finds any then it shows the view again with a warning. The Confirmed value should then be True which will make the post method not check again.

The problem is that even when I can see the warning message the Confirmed value is False which is not what I would expect. Can anyone tell me why this is happening and how to fix it? Thanks.

@if (ViewBag.JobAlreadyExists)
{
    @Html.Hidden("Confirmed", true)
    <p class="text-danger">A job with this address already exists. If you are sure you want to add this job then click the Create button again.</p>
}
else
{
    @Html.Hidden("Confirmed", false)
}


public ActionResult CreateJobAdmin()
{
    ViewBag.JobAlreadyExists = false;

    return View(new Job());
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateJobAdmin([Bind(Include = "Id,SalesAgent,CustomerTitle,CustomerFirstName,CustomerLastName,OwnerOrTenant,PhoneNumber,EmailAddress,Address1,Address2,City,PostCode")] Job job, bool confirmed)
{
    job.TimeCreated = DateTime.Now;
    job.CreatedBy = User.Identity.Name;

    if (ModelState.IsValid)
    {
        if (!confirmed && db.Jobs.Any(j => j.Address1 == job.Address1 && j.Address2 == job.Address2 && j.City == job.City && j.PostCode == job.PostCode))
        {
            ViewBag.JobAlreadyExists = true;

            return View(job);
        }

        db.Jobs.Add(job);
        db.SaveChanges();
        return RedirectToAction("JobDetails", routeValues: new { id = job.Id });
    }

    return View(job);
}


Is This A Good Question/Topic? 0
  • +

Replies To: Hidden field has wrong value

#2 Coding in the name of  Icon User is offline

  • D.I.C Regular

Reputation: 67
  • View blog
  • Posts: 291
  • Joined: 07-July 10

Re: Hidden field has wrong value

Posted 16 October 2016 - 10:25 AM

Found the answer, I have to use this in the post action.

ModelState.Remove("Confirmed");
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1