patel.milanb
patel.milanb

Reputation: 5992

update Index view with the data return in $.ajax success callback... Asp.Net Mvc 3

i have a very simple "InddexView" which is showing the details of the entries which is already in the database. on the same view i have a create entry link. clicking the create link using Ajax.Actionlink to update the div on the same "IndexView" and showing the create view with the textboxes and buttons... Now on the "Create" View.cshtml i am using the $.ajax to create new entries via ajax. entries are getting created in database but not refreshing the main "IndexView" to show the newly created entry.. please help on how to do that ?.

Here is my _Create.Cshtml code which is used to disply all the entries.

    @using (Html.BeginForm()) {
        @Html.ValidationSummary(true)
        <fieldset id="fsShowCreatestatus">
            <legend>Entries</legend>

            <div class="editor-label">
                @Html.LabelFor(model => model.Title)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Title)
                @Html.ValidationMessageFor(model => model.Title)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.Body)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Body)
                @Html.ValidationMessageFor(model => model.Body)
            </div>

            <p>
                <input type="submit" value="Create" id="btnCreate" />
            </p>
        </fieldset>
    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

    <script type="text/javascript">
        $('#btnCreate').click(function (e) {
            var title = $('#Title').val();
            var body = $('#Body').val();
            var postdata = {
                "Title": title,
                "Body": body
            };
            e.preventDefault();
            callajax(postdata);

        });

      function callajax(data) {
          $.ajax({
              url: '@Url.Action("CreateViaAjax","Home")',
              data: data,
              success: function (returnData) {
                  $('#divCreateNew').slideUp(100).fadeOut(50);
                  alert('Ajax-completed');
                  $('#divShowDetails').appendTo('#divEdit');
              },
              error: function (returndata) {
                  $('#divCreateNew').appendTo('#fsShowCreateStatus').html('there was an error while adding the entry');
              }
          });
        }
    </script>

here is my index view which the main view and using for showing partial view(_Create) and the link for creating the new one..
=======================================
<h2>Index</h2>
<div id="divCreateLink">
    <p>
        @Ajax.ActionLink("Create New", "Create","Home", new AjaxOptions { 
                InsertionMode = InsertionMode.Replace,
                HttpMethod = "GET",
                UpdateTargetId = "divCreateNew",

   })


    </p>
</div>

<div id="divCreateNew">

</div>

<div id="divEdit">

</div>

@Html.Partial("PartialCreate")

code gets executed but not refreshing the "IndexView"

seeking help...

Here is my controller action "CreateViaAjax"

public ActionResult CreateViaAjax(Entries entries)
        {
            if (ModelState.IsValid)
            {
                db.DBEntries.Add(entries);
                db.SaveChanges();
                return RedirectToAction("Index");  
            }

            return View(entries);
        }

Here is my Index Action which return the Main View

public ViewResult Index()
        {

            return View(db.DBEntries.ToList());
        }

here is my Create Action which is called when clciked on CreateEntry Link

public ActionResult Create()
        {
            return PartialView("_Create");
        }

=================================

Upvotes: 0

Views: 2510

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039318

Here are a couple of possibilities:

  • Wrap the part that needs to be refreshed in a container and a partial view. Then once the entry is created, in the success callback, send another AJAX request to a controller action which will read the entries and return their refreshed state. When this AJAX call succeeds replace the container with the new contents: $('#entriesContainer').html(result);
  • Because you have the info for the newly created entry in the success callback you could probably manually manipulate the html to append this new entry using $('#entries').append('<li>new entry info</li>');
  • Reload the entire page without using AJAX : window.location.href = '@Url.Action("Index", "Home")';

Upvotes: 1

Related Questions