How to stop JavaScript MVC RedirectToRouteResult?

I am designing a site and trying to be compatible with javascript disabled or enabled.

I have a controller action called as follows ...

public RedirectToRouteResult AddWorkAssignment(int id)
{
    // delegate the work to add the work assignment...

    return RedirectToAction("Index", "Assignment");
}

and my jQuery i'm making a message

$('#someButton').click(function() {
    var id = $('#whereTheIDIs').val();
    $.post('/Assignment/AddWorkAssignment/' + id);
    return false;
});

but RedirectToAction on the controller will do just that. How to stop redirects, or how can I structure the controller and page to handle this, because I want redirection to occur if javascript is turned off.

+3
source share
1 answer

Change your controller to something like this:

public ActionResult AddWorkAssignment(int id)
{
    // do work to add the work assignment....

    if (Request.IsAjaxRequest())
        return Json(true);

    return RedirectToAction("Index", "Assignment");
}

You can also create your own filter attribute ... just like the AcceptVerbs attribute.

HTHS

EDIT: AjaxRequest ActionMethodSelectorAttribute

Kickstart

public class AjaxRequest : ActionMethodSelectorAttribute
{
    public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
    {
        if (controllerContext == null)
            throw new ArgumentNullException("controllerContext");

        return controllerContext.HttpContext.Request.IsAjaxRequest();
    }
}

:

public RedirectToRouteResult AddWorkAssignment(int id)
{
    // do work to add the work assignment....

    return RedirectToAction("Index", "Assignment");
}

[AjaxRequest]
public JsonResult AddWorkAssignment(int id)
{
    // do work to add the work assignment....

    return Json(true);
}
+3

Source: https://habr.com/ru/post/1714261/


All Articles