Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When model is not valid, return to partial view inside a view, with error message

In my asp.net MVC 4 project, I like to safe something from a partial view, which is when a user clicks for "more details". Saving the data is no problem, closing the partial view is no problem, open the partial view is not a problem, it's when my model is not valid (when a user forgets to mark something) The result is that my partial view is returned, but not inside the view where it should be. Its just viewed as a standalone page.

View:

@model Evaluatietool.ViewModels.EvaluatorWijzigenOPViewModel
<h3>@ViewBag.Message</h3>
@using (Html.BeginForm("ChangeEvaluator", "Ontwikkelplan"))
{
    @Html.ValidationSummary(true)
    @Html.HiddenFor(model => model.oldEvalAccount)
    @Html.HiddenFor(model => model.selectedMedewerkerAccount)
    @Html.HiddenFor(model => model.eval);
    @Html.HiddenFor(model => model.countMedewerkers);
...

...
<div class="Buttons">
    <input type="submit" value="Submit" />
    @Ajax.ActionLink("Sluiten", "Evaluatorenlijst", new AjaxOptions { OnSuccess = "HideResultDiv" })
</div>
}

Controller:

[HttpPost]
    public ActionResult ChangeEvaluator(EvaluatorWijzigenOPViewModel ewopvm)
    {
        if (ModelState.IsValid)
        {
            if (ewopvm.selectedObjects != null)
            {
                ewopvm.selectedObjects.Add(ewopvm.selectedMedewerkerAccount);
            }
            else
            {
                ewopvm.selectedObjects = new List<string>();
                ewopvm.selectedObjects.Add(ewopvm.selectedMedewerkerAccount);
            }
            Ontwikkelplannen op = new Ontwikkelplannen();
            Evaluaties e = new Evaluaties();
            foreach (string s in ewopvm.selectedObjects)
            {
                op.ChangeEvaluator(ewopvm.newEvalAccount, ewopvm.oldEvalAccount, s, ewopvm.eval);
            }
            return RedirectToAction("Evaluatorenlijst");
        }
        return PartialView("EvaluatorWijzigenPartial", ewopvm);
    }

The link that calls the partial view

 @Ajax.ActionLink(item.Evaluator1.Naam, "EvaluatorWijzigenPartial", new { id = item.ID,     eval = true }, new AjaxOptions { UpdateTargetId = "EvaluatorWijzigen", OnComplete = "ShowResultDiv"})

Index PageIndex page + partial viewPartial view returned when model.isvalid != true

like image 464
Dylan Slabbinck Avatar asked May 16 '13 13:05

Dylan Slabbinck


People also ask

How do I pass a model into partial view?

To create a partial view, right click on Shared folder -> select Add -> click on View.. Note: If the partial view will be shared with multiple views, then create it in the Shared folder; otherwise you can create the partial view in the same folder where it is going to be used.

How do you show model state error in view?

To pass error to the view we can use ModelState. AddModelError method (if the error is Model field specific) or simply ViewBag or ViewData can also be used.

Can we use model in partial view?

Partial Views can use the Page Model for their data whereas Child Actions use independent data from the Controller. Editor/Display templates pass items from the model to the system but can be overridden by user partial views.

How do I return a partial view from the action method?

How to return a partial view from controller action method? To return a Partial view from the controller action method, we can write return type as PartialViewResult and return using PartialView method.


1 Answers

From what I can see you are using a standard Html.BeginForm POSTing to the ChangeEvaluator controller action which either performs a redirect or returns a partial view if validation fails.

So the behavior you are observing is perfectly normal. You will have to submit this form using AJAX if you want to achieve that:

@using (Ajax.BeginForm("ChangeEvaluator", "Ontwikkelplan", new AjaxOptions { OnSuccess = "handleSuccess" }))
{
    ...
}

and then you could adapt your controller action so that in case of success it doesn't redirect but it returns a Json object containing the url to redirect to:

[HttpPost]
public ActionResult ChangeEvaluator(EvaluatorWijzigenOPViewModel ewopvm)
{
    if (ModelState.IsValid)
    {
        ...
        return Json(new { redirectTo = Url.Action("Evaluatorenlijst") });
    }
    return PartialView("EvaluatorWijzigenPartial", ewopvm);
}

and finally write the handleSuccess javascript function:

function handleSuccess(result) {
    if (result.redirectTo) {
        // The controller action returned a JSON object with the redirectTo property
        // let's redirect to this location:
        window.location.href = result.redirectTo;
    } else {
        // The controller action returned a partial view with the form and the errors
        // So we need to update some containing DIV with it:
        $('#someDivThatCOntainsYourForm').html(result);
    }
}
like image 76
Darin Dimitrov Avatar answered Sep 20 '22 08:09

Darin Dimitrov