1

I have 2 methods (get and post) for view. In post method I call a get method again (because data invalid), but when I see view page again I see with pre-populated data. Why?

        public ActionResult FillForm(string FormID)
    {

                    FillRecordViewModel model = new FillRecordViewModel();

                    model.RefHost = host;
                    model.FormID = FormID;
                    model.Country = new SelectListModel();
                    model.Country.Values = (from i in db.Countries select new SelectListItem() { Text = i.CountryName, Value = i.CountryID.ToString() }).ToList();

                    return View(model);

    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult FillForm(FillRecordViewModel model)
    {
        if (ModelState.IsValid)
        {

        }
        else
        {
            return FillForm(model.FormID);
        }
    }
Oleg Sh
  • 8,496
  • 17
  • 89
  • 159

2 Answers2

0

I imagine it happens because you return FillRecordViewModel model with values with the View in [HttpGet] FillForm. If you don't want the View to pre-populate fields, make sure you don't pass the model so in [HttpGet] FillForm you'd return this return View();.

dima
  • 1,181
  • 1
  • 9
  • 20
0

I assume you are using editor templates like @Html.EditorFor, @Html.TextBoxFor etc.

What you see is the expected behaviour of the MVC editor templates, where the values in the ModelState take precedence over the actual values in the view model. This allows the same posted data to be displayed along with any validation errors after a form was submitted in a post action. (There are some previous questions like this one or this blog post)

If you don“t want this behaviour, you can clear the ModelState before calling return FillForm(model.FormID); on your post action:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult FillForm(FillRecordViewModel model)
{
    if (ModelState.IsValid)
    {

    }
    else
    {
        //You can selectively clear the ModelState for specific properties, ignoring their submitted values
        ModelState.Remove("SomePropertyName");
        //Alternatively, you can clear the whole ModelState
        ModelState.Clear();
        return FillForm(model.FormID);
    }
}

This way, the form that will be displayed will not contain the submitted data. Please note that this also means the form displayed after the post action will not display any validation errors. (You could only remove the values from the ModelState using something like ModelState["SomePropertyName"].Value = null;, but it might be weird for the user if you display a validation error for a field which is now empty or with the default value of your view model)

Hope this helps!

Community
  • 1
  • 1
Daniel J.G.
  • 34,266
  • 9
  • 112
  • 112