1

I am working on MVC-4 application. I have 2 action in 2 different controller like:

Parent

Public ActionResult Detail(int id)
{
  var p = parent.GetById(id);
  ViewBag.Child = TempData["Child"];
  return View(p);
}

Child

Public ActionResult Create(Child child)
{
  if(ModelState.IsValid)
  {
   //code save to db
  }
  TempData["Child"] = child;
  return RedirectToAction("Detail", "Parent", new { id = child.ParentId });
}

I have a parent view and a partial child view. Child view renders inside parent view (Child view contains a form to create new child for parent). When user add new child, we send child data to child controller's create action and after successful save we return user to the same parent from where he/she added the child. For this reason we redirect the user to parent controller's detail action. And if any validation error occur than also we redirect to parent controller's detail action but this time we save the child object inside TempData to keep modelstate error.

My parent detail view is :

.....
......

@if (ViewBag.Child == null)
{
    Html.RenderPartial("_AddChildPartial", new ViewDataDictionary { { "parentId", Model.Id } });
}
else
{
    Html.RenderPartial("_AddChildPartial", ViewBag.Child as xxxx.Models.Child);
}

Here i am first check whether the viewbag contains child object if yes than we pass that child obejct to _AddChildPartial view.To show the model error and data which user filled in the form.The data shows successfully but the model error are not showing.

Can anybody please tell me what i doing wrong here, why model errors are now showing in _AddChildPartial View ?

1 Answer 1

3
TempData["Child"] = child;

You are not storing the full Model State (i.e., validation error information).
You are only storing your Child object's POST values.

Read the POST REDIRECT GET pattern from Kazi Manzur Rashid's blog post.
It'll solve your problem easily.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.