pavilion pavilion - 3 months ago 14
Ajax Question

ASP.NET MVC return back to previous ajax state (page)

I have simple pages for a testing purpose. So I have an Index page that has a drop-down-list to select a country and a button to search which brings up some information as a list of rows in a table.

@using (Ajax.BeginForm("GetList", "test", new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "showResult"
}))


In my controller, it returns a partial view.

[HttpPost]
public ActionResult GetList(int CountryId)
{
var model = db.Names
.Include(x => x.Country)
.Where(x => x.Country.CountryId == CountryId).ToList();

return PartialView("PartialPosting", model);
}


In my PartialPosting view, there is a button to call a modal dialog that can submit a note.

@model IEnumerable<test.Models.Names>
<table class="table table-hover">
<tr>
<th>Note</th>
</tr>

@foreach (var item in Model)
{
<tr>
<td>
@Html.ActionLink("Button", "button", "test", null, new { @class = "btn btn-danger btn-xs modal-link" })
</td>
</tr>
}
</table>

<div id="modal-container" class="modal fade" tableindex="-1" role="dialog">
<div class="modal-content">
<div class="modal-body">
</div>
</div>
</div>

<script>
//jquery function
</script>


When a button is clicked, it goes to a button method in the controller which returns the view that will be shown in a modal for

<div class="modal-body">


Button method:

public ActionResult Button()
{
return View();
}


Button View:

@model test.ViewModels.NoteViewModel

@using (Html.BeginForm("PostNote", "test", FormMethod.Post))
{
@Html.AntiForgeryToken()

@Html.TextAreaFor(model => model.Note)

<input type="submit" value="Submit" />
}


and the PostNote method:

[HttpPost]
public ActionResult PostNote(NoteViewModel model)
{
//codes

--> ?? return RedirectToAction();
}


Everything works,
but here is my problem. When a modal submits the note,


  1. I want the modal to disappear right away.

  2. return back to the previous state where there were a drop-down-list to select a country and a search button && a search result table where I just clicked a button.



Since this involves an ajax response, I am not sure how to bring the correct URL to go back to the previous state.

Answer

You have to make the form submit in the button view (post note form) to be an ajax form submit and in the PostNote action method which handles the form post data from this form, return a json response. In the success callback of the ajax form submit, simply hide/close the modal dialog and you will see your original buttons and dropdown from your first page.

So update your button view (Button.cshtml)to give the form an Id which we will use later for wiring up the ajaxified form submit event later.

@{
    Layout = null;
}
@model test.ViewModels.NoteViewModel

@using (Html.BeginForm("PostNote", "test", FormMethod.Post,new {id="postNoteForm"}))
{
    @Html.AntiForgeryToken()

    @Html.TextAreaFor(model => model.Note) 

    <input type="submit" value="Submit" />
}
<script>
    $(function() {

        $(document).on("submit", "#postNoteForm", function(e) {
                    e.preventDefault();
                    $.post($(this).attr("action"),$(this).serialize(),function(response) {

                        console.log('response from ajax call', response);
                        if (response.status === "success") {
                            $('#modal-container').modal('hide');
                        } else {
                            alert(response.errorMessage);
                        }
                    })
        });

    })
</script>

Assuming your PostNote httppost action method returns a json response with a status & errorMessage property (in case of an error)

[HttpPost]
public ActionResult PostNote(NoteViewModel model)
{
  try
  {
    // to do : Save data
     return Json(new {status="success"});
  }
  catch(Exception ex)
  {
     return Json(new {status="error", errorMessage = ex.Message });
  }
}
Comments