2

I am deleting a row in my webgrid , and redirecting to my GET index as normal after delete. However as expected my view is showing the old deleted row still in the grid. I know this is by design and i should be able to set the Modelstate to clear , or remove the item individually to achieve this :

 ModelState.Remove("id");

Or

 foreach (var key in ModelState.Keys.Where(m => m.StartsWith("id")).ToList())
            ModelState.Remove(key);

Or

 ModelState.Remove("Applicant.ApplicantId"); 

Or even :

ModelState.Clear()

However none have working for me.

Here is my delete method (simplified -all error handling and non necessary code removed )

 public ActionResult DeleteApplicant(int id)
    {

            var q =
                        (from a in context.Applicants
                         where a.ApplicantId == id
                         select a).Single<Applicant>();



            q.ApplicantDocuments.ToList().ForEach(r => context.ApplicantDocuments.Remove(r));

            context.Applicants.Remove(q);
            context.SaveChanges();



        foreach (var key in ModelState.Keys.Where(m => m.StartsWith("id")).ToList())
        ModelState.Remove(key);

        TempData["SuccessMessage"] = "Successfully deleted row.";

        return RedirectToAction("Index");
    }

And here is my call to my delete method from the view :

  , grid.Column(format: (item) => @Html.ActionLink("Delete", "DeleteApplicant",
                                      new { id = item.ApplicantId }, new { @class = "delete-link" }), style: "DeleteButton")

I have looked at various posts on stackoverflow etc but none seem to solve my issue : MVC 3 The View is not being refreshed after model submit

I have tried also tried re-directing to the Index action via jquery and calling the delete controller action with ajaxOptions , but this hasn't worked either.

            , grid.Column(format: (item) => @Ajax.ActionLink("Delete", "DeleteApplicant",
    new { id = item.ApplicantId },
    new  AjaxOptions  { HttpMethod = "GET" , OnSuccess= "reloadGrid" }))

And adding a little script to call the home index:

 function reloadGrid() {
    var pathArray = window.location.pathname.split('/');
    var segment_1 = pathArray[1];
    var newURL = window.location.protocol + "//" + window.location.host + "/" + segment_1 + "/Home/Index";

    $.ajax(
        {
            type: "GET",
            url: newURL,
            data: "{}",
            cache: false,
            dataType: "html",
            success: function (data)
            { $().html(data); }
        })
}

I am obviously doing something wrong. Is there any other way i can force a refresh of the page in a different way or can anyone spot anything obviously wrong in my current approach. Thanks in advance.

Note: I do have my webgrid markup on my Index view and not in a separate partial viewbut i don't think this should be causing this?

Update :

Here is up GET method as requested: (for context, the filters object is used when search button is clicked and page is posted back ,no filters applied in initial page load)

public ActionResult Index(string page)
        {
                /////Peform paging initiation
                int pageIndex = 0;
                if (!string.IsNullOrEmpty(page))
                {
                    pageIndex = int.Parse(page) - 1;
                }

                ////initialize total record count and filter results object
                int totalRecordCount = 0;

                var filters = new ApplicantSearchFilter();

                ////Perform search with paging
                var applicants = this.GetApplicantsPaging(filters ,pageIndex, out totalRecordCount);

                ////Return view type
                var data = new ApplicantViewModel()
                {
                    Filters =filters ,
                    TotalRecordCount = totalRecordCount,
                    ApplicantReportLists = applicants,
                    PageIndex = pageIndex,
                };

                ////return Index view passing data result to build it
                return this.View("Index", data);
            }
        }
Community
  • 1
  • 1
Alicia
  • 1,152
  • 1
  • 23
  • 41
  • can you share your GET method you are Redirecting to? – Krunal Patil May 15 '14 at 11:59
  • Sure , it's up there now – Alicia May 15 '14 at 13:40
  • sorry, I was busy yesterday so could not reply, but if you can see your GET Method accepts a string parameter "page", due to which, when you redirect your Action to "Index" its not working(not able to find this GET Action named Index with no parameters), you need to pass this string parameter when you return, something like this return RedirectToAction("Index", new { page = your_value_to_pass); – Krunal Patil May 16 '14 at 04:40
  • Hi Krunal, thanks for getting back to me. It's going in my Index Action ok , i have a breakpoint in there so it must be something else. – Alicia May 20 '14 at 08:49
  • did you try debugging from your "Index" Method and designer page? if yes did it give any error? Also – Krunal Patil May 20 '14 at 08:55
  • No there are no errors. I know this is built in MVC behavior and Html.Helpers prefers the values in the ModelState collection over the actual model values. so this is how its supposed to work. But i need a way of refreshing my page after the delete and essentially overriding this default behavior. – Alicia May 20 '14 at 10:07

1 Answers1

1

I have finally managed to get this working.

If it helps anyone else here is what i did in the end. I used a solution posted by Dror here : How to achieve edit and delete on Webgrid of MVC3 Razor? . Where he turned a GET delete call from the webgrid into a post. Not exactly what i was looking for but it works.

Does anyone have a better , alternative solution ?

View Code :

added Function :

@functions{
  string Delete(dynamic p)
  {
    string actionController = Url.Action("Delete", "Admin", new {id=p.AccountId});
    return "<form style='display:inline;' method='post' action='" + actionController + "'><input type='submit' value='Delete' onclick=\"return confirm('Are you sure?')\"/></form>";
  }
}

and changed my delete call in my webgrid to :

grid.Column(header: "", format: p => Html.Raw(Delete(p)))

In the Controller:

[HttpPost]
public ActionResult Delete(int id)
{
   PerformDelete(id);
   return RedirectToAction("Index");
}
Community
  • 1
  • 1
Alicia
  • 1,152
  • 1
  • 23
  • 41
  • I think your Index() action has got cached. We had the same problem. I used to set the OutputCache(Duration=0, VaryByParam="*"). you can set VaryByParam="page" since you are getting the page index. – Sravan May 25 '14 at 12:45
  • Hi Sravan, thanks for the tip! I tried decorating my Index method with the attribute [OutputCache(Duration=0, VaryByParam="page")] and passing in the page param on redirect, but i had the same result.i.e results not refreshing. – Alicia May 26 '14 at 16:42