Question

I finally managed to get my PartialView updating using Ajax. The purpose of the partial view is a sidebar widget that displays the contents of a registration and allows the removal of items from the registration.

An abbreviated version of the PartialView is as follows:

<table id="item-entries">
    @foreach (var item in Model.Items)
    {
        <tr>
            <td>@item.Name</td>
            <td>@item.Price</td>
            <td>
                @using (Ajax.BeginForm("RemoveItemEntry", "Registration", new AjaxOptions { UpdateTargetId = "item-entries" }))
                {
                    <button type="submit" name="ItemId" value="@item.ItemId">×</button>
                }
            </td>
        </tr>
    }
</table>

And here is an abbreviated example of the action:

[HttpPost]
public ActionResult RemoveItemEntry(ItemViewModel data)
    {
      // Perform logic to remove the item from the registration 
      // then return the PartialView with updated model

      return PartialView("~/Views/Partials/ItemEntries.cshtml", model);
    }
}

This works great now however I don't want to offer a broken experience for those that have JavaScript disabled. If you post the form with JavaScript disabled the action still executes correctly but you are redirected to a url which renders the PartialView and nothing else. What I would like to happen is that for users that have JavaScript disabled they are redirected back to the original page from which the form was posted.

Is this achievable?

Était-ce utile?

La solution

So you have two options here:

The first one is to change the Action method to the following:

[HttpPost]
public ActionResult RemoveItemEntry(ItemViewModel data)
{
    // Perform logic to remove the item from the registration 
    // then return the PartialView with updated model

    if (Request.IsAjaxRequest())
    {
          return PartialView("~/Views/Partials/ItemEntries.cshtml", model);
    }
    else
    {
          // return the initial View not the parial fie
    }
}

The second option is to replace you Ajax form with a normal that call a Action method that return the initial View. Then you'll have to write a jQuery code that make an AJAX call when the form is submitted, but it'll make the AJAX call to a second method that will return the PartialView.

Autres conseils

My solution goes as follows -

In the intial view, you can induce a cookie as follows -

<script>
    document.cookie = "JSEnabled=1; path=/";
</script>

Then for JS enabled browsers, when you make a POST, cookie will be coming in Request as shown below -

enter image description here

And when you have JavaScript disabled browsers, cookie will be null as shown below -

enter image description here

So based on that cookie value, whether null or available, make a redirect or Return view() as per your requirement.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top