Question

I've got a trouble with execute ajaxified HttpPost action method. Breakpoint in ActionMethod Publish isn't even fire, Html version of this method return: resource cannot be found (404). The name of the controller is okay, logged in user's role is okay, PartialView exists. What can be a reason?

This is a view:

<div id="info"></div>


    @if (User.IsInRole("admin") && item.IsPublished == false)
    {
        <p>
            @Ajax.ActionLink("Publish", "Publish", new { id = item.RecommendationID }, new AjaxOptions() { Confirm="Are you sure?", HttpMethod="POST", UpdateTargetId="info" })
        </p>
    }

This is Action Method:

    [HttpPost]
    [Authorize(Roles = "admin")]
    [ValidateAntiForgeryToken]
    public ActionResult Publish(int? id) 
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }

        Recommendation recommendation = db.Recommendations.Find(id);

        if (recommendation == null)
        {
            return HttpNotFound();
        }

        recommendation.IsPublished = true;
        db.SaveChanges();

        return PartialView("RecommendationPublished");
    }

Edit: Okay - now I know that HttpPost attribute caused my problem - with HttpGet works properly. But in that shape this operation will be insecure (updating database field). How to write it and maintain safety rules?

Était-ce utile?

La solution

As far as I know, you cannot use the AntiForgeryToken along with the Ajax.ActionLink. You'll need to parse the forgery token with some javascript and append it to your post request.

How to include the @Html.AntiForgeryToken() when deleting an object using a Delete link

If you don't want that, remove the forgery token. Also make sure you're using jquery.unobtrusive-ajax.js

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top