0
votes

I have a simple create action that save a product to DB. after saving the product I have used return View(new Product()); to reset the form fields but the form show the old data(the data before submit the form). Also I use return View(new Product(name="test")); but it does not work too. what is the problem? the product is saved to DB correctly (it means ModelState.IsValid is true). I don Not want to use RedirectToAction.

    [HttpPost]
    public ActionResult New(Product product)
    {
        if (ModelState.IsValid)
        {
            product.SubmitDate = DateTime.UtcNow;
            productRepository.Add(product);
            productRepository.Save();

            //ViewBag.Message = "product is saved";
            return View(new Product());
        }

        return View(product);
    }
2

2 Answers

2
votes

I think the recommended practice is to use RedirectToAction() but if you want to try it your way, you could try

 ModelState.Clear();
 return View(new Product());
0
votes

If you intend to modify a property which is already in the model state you will need to remove it or the HTML helpers that are bound to this value would always use the value in the model state and not the one that you modified:

ModelState.Remove("SubmitDate");
product.SubmitDate = DateTime.UtcNow;
return View(product);

And if you want to clear all properties it would be better to redirect or clear the entire model state collection: ModelState.Clear();