views:

274

answers:

1

I am designing a site and am trying to be compatible with javascript turned off or on.

I have a Controller Action named as follows...

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

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

and my jQuery I do a post

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

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

+3  A: 

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 could create your own filter attribute too... much like the AcceptVerbs attribute.

HTHs
Charles

EDIT: AjaxRequest ActionMethodSelectorAttribute attribute

Kickstart from here

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();
    }
}

Then your controller:

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);
}
Charlino