3

I made a form with @using(Ajax.BeginForm){}. It posts to a method in my controller that returns a PartialViewResult. It works fine when everything is valid, but what should I return if it's not (e.g., the modelstate is not valid)? How Ajax.BeginForm can manage the error? What I return to manage the Failure?

@using(Ajax.BeginForm("Create", "Room", new AjaxOptions { HttpMethod="POST",
UpdateTargetId="formRoom", InsertionMode= InsertionMode.Replace, onFailure =??})) {

public PartialViewResult Create(Movie mov)
{
        if (ModelState.IsValid)
        {
            db.Save(mov);
            return PartialView("CreateResult", mov);
        }
        return null;            
}

Thanks!

2 Answers 2

3

You may return another View.

e.g. return PartialView("MyErrorView");

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

1 Comment

For Ajax Calls you can also return JSON like "return Json(new { Result = "Failure", Message = "Model Invalid"},JsonRequestBehavior.AllowGet); and parse this result in the success/failure ajax call.
1

Just return Create action with the model to display the errors (the same as you returned on your get):

    [HttpPost]
    public PartialViewResult PartialCreate(Album album)
    {
        if (ModelState.IsValid)
        {
            db.Albums.Add(album);
            db.SaveChanges();
            return PartialView("Index");
        }

        ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
        ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
        return PartialView(album);
    }

6 Comments

you cannot return that, you cannot convert it. Try to compile it.
Just made a sample. It compiles without any errors. Or is it because the Ajax.BeginForm? I'll try that as well.
before you put return View();
ah, sorry, that was because I didn't see in the first place that you used a PartialView. I had already changed it when you added your comment. Does it work now?
yes... but I just edit my question... that was not what I intend to ask
|

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.