【问题标题】:Unable to call Post ActionResult from View无法从视图调用 Post ActionResult
【发布时间】:2015-06-19 04:51:30
【问题描述】:

我试图通过在我的控制器中调用 ActionResult 从我的视图发出 POST 请求。基本上,视图中有一个事件列表,用户可以通过单击事件来查看事件的详细信息。这部分有效。但是,一旦他们查看详细信息,他们也可以注册该活动。这是不工作的部分。

我在视图中尝试的示例操作:

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

这应该访问此操作结果:

[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");
}

但是,我收到 404 错误。我认为它找不到actionresult?

但是,详细信息操作结果在同一页面上并且有效:

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

    return View(evenement);
}

我不明白为什么注册会给出 404。有什么想法吗?

【问题讨论】:

    标签: c# html asp.net asp.net-mvc


    【解决方案1】:

    您不能使用ActionLink 发出POST 请求。您有以下选择。

    1. 使用submit 按钮发布表单
    2. 使用Ajax.ActionLink()
    3. 使用jQuery.ajax

    我会推荐submit 按钮,因为我觉得它比其他按钮更简单。

    作为第一种方法的示例。试试这个

    剃须刀:

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

    控制器:

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

    【讨论】:

      【解决方案2】:

      这是因为您的 Detail Action 方法是 Get 方法,而您的 SignUp Action 方法装饰有 [HttpPost] 属性,这意味着它是 Post 方法。从您的操作方法中删除 HttpPost,它将运行。

      编辑:

      出于您的目的,我建议您使用@Lmadoddin Ibn Alauddin 的方法 建议。 您可以将您的数据放在form 标签下并使用submit 按钮提交(我不建议您查看您的代码,您也没有发布HTML)。 要么: 您可以使用 type: 'POST' 拨打 $.ajax() 并传递您的数据,例如 data: {id: 'idvalue'}。

      希望这会对您有所帮助。如果您遇到任何问题,请告诉我。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-21
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多