Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC return PartialViewResult

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!

like image 553
elranu Avatar asked Jun 10 '26 10:06

elranu


2 Answers

You may return another View.

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

like image 134
kanchirk Avatar answered Jun 12 '26 04:06

kanchirk


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);
    }
like image 29
slfan Avatar answered Jun 12 '26 03:06

slfan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!