Ajax.BeginForm不提交表单值

时间:2016-04-21 17:22:31

标签: ajax asp.net-mvc asp.net-mvc-4 ajax.beginform

我想在我的ASP.NET MVC项目中使用Ajax.BeginForm,下面是.cshtml文件上的代码

'----List

我的行动在下面,但我无法在行动中获得张贴的参数。为什么呢?

@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?
    ....
 }

到web.config

<add key="UnobtrusiveJavaScriptEnabled" value="true" />

捆绑

如果我在.cshtml上使用Html.BeginForm而不是Ajax.BeginForm,一切正常。

2 个答案:

答案 0 :(得分:0)

尝试确保您要发布到的方法使用[HttpPost]属性进行修饰,以确保它可以接收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>

答案 1 :(得分:0)

使用Ajax.BeginForm,在您的控制器中,您需要按如下方式请求[“您的输入名称]”:

public ActionResult ActionName()
{ 
   string Posted = Request["posted"];

    //Some more code
}