Search code examples
asp.netasp.net-mvc-3formcollection

ASP.NET MVC3 fill in form again after post using FormCollection


So what I do is, I have a controller that checks if the input in my form is correct. If it's not, it puts an error message in the ViewBag and returns the view. Like this (unimportant stuff left out):

var name = formCollection.Get(cr.Category.name + "-name-" + i).Trim();
var dateOfBirth = formCollection.Get(cr.Category.name + "-dateOfBirth-" + i).Trim();
var passportno= formCollection.Get(cr.Category.name + "-passportno-" + i).Trim();

if (name.Equals("") || dateOfBirth.Equals("") || passportno.Equals(""))
{
     ViewBag.ErrorMessage = "Please fill in all required fields at " + cr.Category.naam;
     return View("BulletinForm3");
}

And my view looks like this (unimportant stuff left out):

<input name="@(cr.Category.naam)-name-@i" value="" />
<input name="@(cr.Category.naam)-dateOfBirth-@i" value="" />
<input name="@(cr.Category.naam)-passportno-@i" value="" />

@if (ViewBag.ErrorMessage != null)
{
     <p class="error">@ViewBag.ErrorMessage</p>
}

So what happens when you forget to fill in a required field? It returns the view and displays the error message, BUT all the fields that were already filled in are empty again... So what I want to do is use the FormCollection to fill them back in after it returns the view. I put the FormCollection in the ViewBag like this:

ViewBag.ErrorMessage = "Please fill in all required fields at " + cr.Category.naam;
ViewBag.FormCollection = formCollection;
return View("BulletinForm3");

And changed this in the view:

<input name="@(cr.Category.naam)-name-@i" value="@if (ViewBag.FormCollection != null) { ((FormCollection)ViewBag.FormCollection).Get(cr.Category.naam + "-name-" + i);}" />

However, it doesn't fill in the input fields with the values of the FormCollection... The FormCollection isn't empty (tested it) and the names are the same (the counter (i) doesn't change or something). What am I doing wrong?

Thanks in advance


Solution

  • As I couldn't find a solution, I decided to use Javascript validation instead of validating in the controller. Now, there is no postback so no need to fill the fields in again.