1

I am new to MVC and I will try to elaborate my issue carefully. I have a controller with 2 Action Methods, one of which is a POST method:

[AllowAnonymous]
public ActionResult Register()
{
    RegisterViewModel registerModel = new RegisterViewModel();
    //Some Code to populate dropdowns for user to select
    return View(registerModel);
}

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    try
    {
        if (ModelState.IsValid)
        {
            //insert data in tables
            RedirectToAction("Register");
        }
        AddErrors(result);
    }
    catch (Exception ex)
    {
        ModelState.AddModelError("", "Error Processing Your Request");
    }

    // If ModelState.IsValid returns false show the form with posted data by user
    return RedirectToAction("Register", model);
}

Now when form is posted all the data filled by user is not persisted. I want to display the same form to user with his posted data and fill missing details to complete registration.

Sorry if this is a very basic question. How do I persist the data on the same view.

Peter B
  • 22,460
  • 5
  • 32
  • 69
LearningPal
  • 554
  • 2
  • 12
  • 27
  • If its invalid, then you use `return View(model);` to return the view and display the validation errors (not `RedirectToAction(...)`) –  Aug 23 '17 at 12:06
  • return RedirectToAction("Register", model) calls the same function again – Musab Aug 23 '17 at 12:15
  • I also have EditorTemplate which loads on the view and when I return View(model); Then I get the error as **The ViewData item that has the key 'EmploymentType' is of type 'System.Int32' but must be of type 'IEnumerable'.** – LearningPal Aug 23 '17 at 12:20
  • 1
    Please start a new question for that, because that is not directly related to the subject matter of this question. – Peter B Aug 23 '17 at 12:25
  • Gotcha Thanks a lot – LearningPal Aug 23 '17 at 12:27
  • 1
    For that error, refer [this question/answer](https://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) - you need to repopulate and SelectLists used in your view before you return it –  Aug 23 '17 at 12:30

2 Answers2

2

First Edit Your Model With DataAnnotations [Required] which You don't want to be empty like:
[Required(ErrorMessage ="Name Can't be Empty.")]
public string Name { get; set; }

Now edit your controller some thing like.

if (ModelState.IsValid)
{
  //insert data in tables
      RedirectToAction("Register");
}
else
{
return View();
}
Pashupati Khanal
  • 733
  • 3
  • 11
2

Instead of return RedirectToAction("Register", model); use return View(model);.

Here is a nice blog explaining the differences.

Peter B
  • 22,460
  • 5
  • 32
  • 69
Rahul Mistry
  • 192
  • 2
  • 15