AlexW
AlexW

Reputation: 2587

RedirectToAction doesn't seem to be working

My add/edit code below should redirect back to my index action but it doesn't seem too, it just stays in the same state.

The update function is run (I've checked via debug) then it should return the index view with no dialog and the update data at the moment the dialog just stays and the data isn't updated in the table.

Anyone knows what is wrong? I've also run a capture on it too, nothing I can see there either, just seems to not return the view back:

[HttpPost]
public ActionResult AddEditRecord(tblEquipment Equipment, string cmd)
{
    if (ModelState.IsValid)
    {
        switch (cmd)
        {
            case "Add":
                try
                {
                    db.tblEquipments.Add(Equipment);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                catch { }
                break;
            case "Update":
                try
                {
                    tblEquipment Item = db.tblEquipments.Where(m => m.ID == Equipment.ID).FirstOrDefault();
                    if (Item != null)
                    {
                        Item.AssetNo = Equipment.AssetNo;
                        Item.MachineName = Equipment.MachineName;
                        db.SaveChanges();
                    }
                    return RedirectToAction("Index");
                }
                catch { }
                break;
            }
        }

        if (Request.IsAjaxRequest())
        {
            return PartialView("_AddEdit", Equipment);
        }
        else
        {
            return View("AddEdit", Equipment);
        }
    }
}

EDIT: I put the return at the very beginning of the function (below) and it just ignored it and updated the table!

public ActionResult AddEditRecord(tblEquipment Equipment, string cmd)
{
    return RedirectToAction("Index");
    if (ModelState.IsValid)

EDIT 2: Ok I think it might be an ajax issue.

Looking at this question

My chstml generates the below form, do I need to add a return false to that? CSHTML

@using (Ajax.BeginForm("AddEditRecord", "UserEquipment", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "equipmentDialog" }))

HTML GENERATED

<form id="form0" action="/UserEquipment/AddEditRecord/752" method="post" data-ajax-update="#equipmentDialog" data-ajax-mode="replace" data-ajax-method="POST" data-ajax="true" novalidate="novalidate" jQuery18206614934889497519="43">

Upvotes: 0

Views: 572

Answers (1)

AlexW
AlexW

Reputation: 2587

sorted!

I modified the ajax options as per below, it now works succesfully

<script>
    function onSuccess() {
        window.location.href = '@Url.Action("Index","UserEquipment")'
    }
</script>


@using (Ajax.BeginForm("AddEditRecord", "UserEquipment", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "equipmentDialog", OnSuccess="onSuccess()" }))

Upvotes: 2

Related Questions