简体   繁体   中英

Unable to call Post ActionResult from View

I am trying to make a POST request from my View by calling an ActionResult in my Controller. Basically there are a list of events in the view and the user can view the details of the event by clicking the event. This part works. However, once they view the details they also have the ability to sign up for the event. This is the part which is not working.

A sample action I'm trying from the view:

@Html.ActionLink("SignUp", "SignUp", new {id = "2"}, null)

This should access this action result:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SignUp(int id)
{
    if (ModelState.IsValid)
    {
        var registratie = new Registratie(User.Identity.GetUserId(), id);
        _db.Registraties.Add(registratie);
        _db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View("Index");
}

However, I am getting a 404 error. I think it can't find the actionresult?

The details action result is on the same page however and that works:

// GET: /EventPlanner/Details/5
public ActionResult Details(int id)
{
    var evenement = _db.Evenementen.Single(e => e.ID == id);

    return View(evenement);
}

I don't understand why the signup gives a 404. Any ideas?

You cant use ActionLink for making POST request. You have following alternatives.

  1. Use submit button to post form
  2. Use Ajax.ActionLink()
  3. Use jQuery.ajax .

I would recommend submit button because I feel it is simpler than the rest.

As an example for first approach. Try this

Razor:

@using (@Html.BeginForm("ActionName", "ControllerName"))
{
    <input type="hidden" name="id" value="2" />
    <input type="submit" value="Post" />
}

Controller:

public class ControllerNameController : Controller
{
       [HttpPost]
        public ActionResult ActionName(string id)
        {
            //Your stuff

            return View();
        }
}

Its because your Detail Action method is a Get method while your SignUp Action method is decorated with [HttpPost] attribute, which means its a Post method. Remove HttpPost from your action method and it will run.

Edit:

For your purpose, I would recommend you use approaches @Lmadoddin Ibn Alauddin suggested. You can put your data under form tag and submit it using submit button(I don't recommend by looking at your code and you have not posted HTML too'). Or: You can make $.ajax() call with type: 'POST' and pass your data like data: {id: 'idvalue'}.

Hope this will help you. Let me know if you face any problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM