index.cshtml
<script type="text/javascript">
function OnSuccessComment(data) {
alert(data.resultMessage);
}
</script>
@using (Ajax.BeginForm(new AjaxOptions
{
Url = Url.Action("AddCommentAjax"),
OnSuccess = "OnSuccessComment",
HttpMethod = "POST"
}))
{
@Html.TextArea("comment")
<input type="submit" value="Добавить комментарий" />
}
HomeController.cs
namespace WebApplication12.Controllers
{
public class HomeController : Controller
{
private static List<string> _comments = new List<string>();
public ActionResult Index()
{
return View(_comments);
}
[HttpPost]
public ActionResult AddComment(string comment)
{
//необходимые действия
return View();
}
[HttpPost]
public ActionResult AddCommentAjax(string comment)
{
//необходимые действия
return Json(new { resultMessage = "Ваш комментарий добавлен успешно!" });
}
}
}
问题是按钮点击不会调用函数AddCommentAjax
。如何解决?有什么问题?
答案 0 :(得分:1)
@using (Ajax.BeginForm("AddCommentAjax", "Home", new AjaxOptions { OnSuccess = "OnSuccessComment",
HttpMethod = "POST"
}))
尝试这样的事情
不要忘记包含javascript文件:
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>