0

I have a Controller Action which returns a JsonResult instead of a View. Depending on whether or not the method completed successfully, I need to add and execute a Javascript. I've added an OnActionExecuted ActionFilter to the method to generate and add the script, but because it's returning a JsonResult, I don't have a ViewResult to which I can add my script.

I'm a bit out of ideas on this. Does anyone have a solution to this problem or know of another way to approach this issue?

Controller method:

[InsertJavascript]
public async Task<ActionResult> Create(CreateAccountPageV2 currentPage, CreateAccountViewModel model)
{
    //some logic here
    
    return return Json(new
            {
                success = true,
                redirectUrl = false,
                html = partialViewToString,
                invalidFields = InvalidFields
            });
}

Action Filter:

[AttributeUsage(AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class InsertJavascriptAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var jsonResult = filterContext.Result as JsonResult;

            if (jsonResult == null)
            {
                return;
            }
            var script = GenerateMyJavascript();

            // some way to send the script to View and execute it
        }
}

Edit: The request is made from an Ajax Form contained in a Partial View.

Partial View file where the request is made to the Controller:

@model CreateAccountViewModel

    @using (Ajax.BeginForm(null, null, new AjaxOptions
    {
        HttpMethod = "Post",
        Url = Model.Url,
        OnBegin = @OnBeginId,
        OnSuccess = @OnSuccessId,
        OnFailure = @OnFailureId
    }, new
    {
        @class = "form--tight",
        data_component = "Auth",
        data_auth_type = "create",
        data_id = @guid,
    }))
    {
        <fieldset>
            // input fields

            <div class="Auth-createAccount-submitContainer">
                <p class="required">*@Model.RequiredFieldLabel</p>
                <button type="submit" id="createFormSubmitBtn" class="btn btn-primary Auth-createAccount-submitButton">
                </button>
            </div>
        </fieldset>
    }
M. Chris
  • 161
  • 2
  • 14

0 Answers0