我想在我的ASP.NET MVC项目中使用Ajax.BeginForm,下面是一个.cshtml文件的代码
@using (Ajax.BeginForm("ActionName", "ControllerName", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "DivName" }))
{
<input type="hidden" name="posted" id="posted" value="5" />
<input type="submit" id="sBtn" value="Submit" />
}我的动作在下面,但我不能在动作中获得张贴的参数。为什么?
[HttpPost]
public ActionResult ActionName(string posted)
{
//posted is null why?
....
}我已经添加了
<add key="UnobtrusiveJavaScriptEnabled" value="true" />转到web.config
和
"~/Scripts/jquery.unobtrusive-ajax.min.js"捆绑
如果我在.cshtml上使用Html.BeginForm而不是Ajax.BeginForm,一切都会正常工作。
发布于 2017-12-22 18:32:15
使用Ajax.BeginForm,您需要在控制器中请求“您输入的名称”,如下所示:
public ActionResult ActionName()
{
string Posted = Request["posted"];
//Some more code
}发布于 2016-04-22 01:24:10
尝试确保使用[[HttpPost]](https://msdn.microsoft.com/en-us/library/system.web.mvc.httppostattribute(v=vs.118%29.aspx)属性修饰您要发送到的方法,这将确保它可以接收POST请求:
[HttpPost]
public ActionResult ActionName(string posted)
{
}除此之外,您的代码看起来应该像预期的那样工作。以下示例应实际演示这两种情况:
HomeController.cs
using System;
using System.Web.Mvc;
using System.Collections.Generic;
namespace PostingExample
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(string posted, bool isAjax = false)
{
return Content(String.Format("{0} was posted. {1}",posted, isAjax ? "(via AJAX)" : ""));
}
}
}Index.cshtml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Post Testing</title>
</head>
<body>
<h2>Normal Form</h2>
@using (Html.BeginForm("Index", "Home"))
{
<input type="hidden" name="posted" id="posted" value="5" />
<input type="submit" id="sBtn" value="Submit" />
}
<h2>AJAX Form</h2>
@using (Ajax.BeginForm("Index", "Home", new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "DivName" }))
{
<input type="hidden" name="posted" id="posted" value="5" />
<input type='submit'>
}
<!-- jQuery and related scripts -->
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script src='http://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js' />
</body>
</html>https://stackoverflow.com/questions/36776529
复制相似问题