我有一个控制器动作,它返回一个 JsonResult 而不是一个视图。根据方法是否成功完成,我需要添加并执行 Javascript。我在方法中添加了一个OnActionExecuted ActionFilter 来生成和添加脚本,但是因为它返回一个 JsonResult,所以我没有可以添加我的脚本的 ViewResult。
我对此有点想法。有没有人有这个问题的解决方案或知道解决这个问题的另一种方法?
控制器方法:
[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
});
}
动作过滤器:
[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
}
}
编辑:请求是从包含在部分视图中的 Ajax 表单发出的。
向控制器发出请求的部分视图文件:
@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>
}