Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RedirectToAction after ajax form submit in Asp.net Core

I have a view named Index and a PartialView named '_Addbook' that shown as a bootstrap modal. In the partialView insert data into database using ajax form.

Index view :

<div class="panel panel-primary">
<div class="panel-body">
    <div class="btn-group">
        <a class="btn btn-primary marginbutoon" id="showBookgroup" data-toggle="modal" asp-action="AddBook"
           data-target="#modal-book">
            <i class="glyphicon glyphicon-plus"></i>
            Add Book
        </a>
    </div>
</div>

Partialview :

 @model WebApplication1.Models.Book
<form asp-controller="Home" asp-action="AddBook" id="myform"
  data-ajax="true" data-ajax-method="POST"
  data-ajax-mode="replace" data-ajax-update="#myform">



        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title" id="myModalLabel">Add Book</h4>
        </div>


        <div class="modal-body form-horizontal">
            <div class="row">
                <div class="form-group">
                    <label asp-for="BookName" class="col-sm-3 control-label"></label>
                    <div class="col-lg-6">
                        <input asp-for="BookName" class="form-control" />
                        <span asp-validation-for="BookName" class="text-danger"></span>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal-footer">
            <input type="submit" class="btn btn-primary" value="Submit" />
        </div>

Controller :

 [HttpGet]
    public IActionResult AddBook()
    {
        var book = new Book();
        return PartialView("_AddBooks", book);
    }



    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult AddBook(Book model)
    {
        if (ModelState.IsValid)
        {
            using (var db = _Context.GetRequiredService<ApplicationDbContext>())
            {
                db.bookgroups.Add(model);
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }
        else
        {
            return PartialView("_Addbooks", model);
        }
    }

The data is stored correctly in the database and modal hide after submit but index view shows Mixed up. How can i Redirect after ajax submit?

like image 405
topcool Avatar asked Nov 03 '17 22:11

topcool


1 Answers

Your current form is setup to do ajax form post. So when the response is received from the server, it will replace the inner html of the form tag. So with your current code, it will basically makes a GET call to the Index action and the response of that will be loaded to the form tag.

If you want to do a redirect, but still want to have the model validation works, You may return a view result back, which has some javascript code which does the redirection.

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult AddBook(Book model)
{
    if (ModelState.IsValid)
    {
        //Your code to store data     
        return PartialView("_AddedSuccessfully");
    }
    return PartialView("_AddBooks", model);
}

And in the _AddedSuccessfully.cshtml partial view will have only the below content, which is the javascript for redirect to /Home/Index

<script>
    window.location.href = '@Url.Action("Index","Home")';
</script>

EDIT : As per the comment

how can i make it dynamically. because i have several partial view in my project and i want pass ControllerName and ActionName as a parameters to _AddedSuccessfully.cshtml?

You can pass it from your view to the action method and from there to the partial view

Just add a hidden input element to the Add form, just above your submit button and use Url.Action helper method to generate the url you want to redirect to, after saving successfully.

<input type="hidden" name="redirectUrl" value="@Url.Action("Index","Home")" />
<input type="submit" class="btn btn-primary" value="Submit"/>

Now, add a new parameter to your action method with the same name as the hidden input. Pass that string value as the model of the view when you call the PartialView method for _AddedSuccessfully view.

[HttpPost]
public IActionResult AddBook(Book model,string redirectUrl)
{
    if (ModelState.IsValid)
    {
        // to do : Save   
        return PartialView("_AddedSuccessfully", redirectUrl);
    }
    return PartialView("_AddBook", model);
}

Now you need to udpate the partial view to be strongly typed to string and use the model of the view for redirect.

@model string
<script>
    window.location.href = '@Model';
</script>
like image 75
Shyju Avatar answered Sep 27 '22 20:09

Shyju