3

In my controller I have the following code:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(AdEntry adentry)
    {

            adentry.adDate = DateTime.Now;
            adentry.adExpirationDate = DateTime.Now.AddDays(32);
            adentry.adConfirmationID = rKeyGen(8);

            if (ModelState.IsValid)
            {
                db.Items.Add(adentry);
                db.SaveChanges();
                TempData["Summary"] = adentry;
                return RedirectToAction("Index");
            }

        return View(adentry);
    }

In my Model I have this property:

   [Required(ErrorMessage = "Confirmation Id is Required.")]
    [StringLength(8, ErrorMessage = "{0} is too long.")]
    public virtual String adConfirmationID { get; set; }

When I try to create a new Item ModelState.IsValid = false. The error I get is that Confiramtion Id is Required. I am setting the adConfirmationID = to a value right above the check. How can I get this check to pass?

4

2 回答 2

3

试试这个:

ModelState.Remove("adConfirmationID")

在检查之前放置此代码ModelState.IsValid

这将解决您的问题。

于 2013-09-18T16:54:32.320 回答
0

有两种方法可以处理此问题,一种是通过此方法从 ModelState 中删除更新/无效字段

ModelState.Remove("foo");

或者您必须使用隐藏字段将值从 View 传递给控制器

 <input type="hidden" asp-for="foo"/>
于 2020-06-24T07:47:54.440 回答