Partial View With ChildActionOnly Attribute issue
I have partial view rendered by jquery and I want to refresh the view using jquery. Here is what my code looks like.
<div id="left">
<input type="button" id="refresh" value="refresh" />
@Html.Partial("_LeftColumn", new ColumnViewModel { Attempt= DateTime.Now })
</div>
<script type="text/javascript">
$('#refresh').click(function () {
$.ajax({
type: "post",
dataType: "html",
url: 'Home/LeftColumnData',
data: {},
success: function (response) {
$('#left').html(response);
}
});
});
</script>
and in control开发者_高级运维ler action i wrote like this
[ChildActionOnly]
public PartialViewResult LeftColumnData()
{
var Column= new ColumnViewModel { Attempt= DateTime.Now };
return PartialView("_LeftColumn", Column);
}
I don't want user to request ColumnData directly from the browser except via ajax but with this approach I'm getting the error below.
What should I do to remove ChildActionOnly attribute and allow to request view directly? What are the alternatives to this problem?
you can use AjaxOnly
[AjaxOnly]
[HttpPost]
public ActionResult LeftColumnData()
{
var Column= new ColumnViewModel { Attempt= DateTime.Now };
return PartialView("_LeftColumn", Column);
}
here is how you can make one
public class AjaxOnlyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if(!filterContext.HttpContext.Request.IsAjaxRequest())
filterContext.HttpContext.Response.Redirect("/error/404");
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
}
}
and use it like
[AjaxOnly]
public ActionResult AjaxActionMethod()
{
....
}
If you intend to access this action directly you need to remove the [ChildActionOnly]
attribute:
public PartialViewResult LeftColumnData()
{
var Column = new ColumnViewModel { Attempt = DateTime.Now };
return PartialView("_LeftColumn", Column);
}
Also from what I can see you are nowhere using this action as a child action. All you do is to render some partial:
@Html.Partial("_LeftColumn", new ColumnViewModel { Attempt= DateTime.Now })
This doesn't invoke your child action. It simply inserts the _LeftColumn.cshtml
partial in the given location.
A child action is invoked with the Html.Action or Html.RenderAction helpers:
@Html.Action("LeftColumnData")
But because you want this action to also be accessible from an AJAX call you should remove the ChildActionOnly attribute.
You can read more about differences between RenderPartial and RenderAction on the following blog post.
There is an [AjaxOnly] attribute provided in the ASP.NET MVC 3 Futures collection. It's a part of the official ASP.NET MVC Codeplex site that provides features before they are officially included in a future version of ASP.NET MVC.
You can download it here. To use it, add a reference to the Microsoft.Web.Mvc assembly included in the release package.
There is an explanation of the attribute on this page.
精彩评论