首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ajax.BeginForm不提交表单值

Ajax.BeginForm不提交表单值
EN

Stack Overflow用户
提问于 2016-04-22 01:22:31
回答 2查看 1.5K关注 0票数 0

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

代码语言:javascript
复制
@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" />
}

我的动作在下面,但我不能在动作中获得张贴的参数。为什么?

代码语言:javascript
复制
[HttpPost]
public ActionResult ActionName(string posted)
{ 

   //posted is null why?
    ....
 }

我已经添加了

代码语言:javascript
复制
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

转到web.config

代码语言:javascript
复制
"~/Scripts/jquery.unobtrusive-ajax.min.js"

捆绑

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

EN

回答 2

Stack Overflow用户

发布于 2017-12-22 18:32:15

使用Ajax.BeginForm,您需要在控制器中请求“您输入的名称”,如下所示:

代码语言:javascript
复制
public ActionResult ActionName()
{ 
   string Posted = Request["posted"];

    //Some more code
}
票数 1
EN

Stack Overflow用户

发布于 2016-04-22 01:24:10

尝试确保使用[[HttpPost]](https://msdn.microsoft.com/en-us/library/system.web.mvc.httppostattribute(v=vs.118%29.aspx)属性修饰您要发送到的方法,这将确保它可以接收POST请求:

代码语言:javascript
复制
[HttpPost]
public ActionResult ActionName(string posted)
{ 

}

除此之外,您的代码看起来应该像预期的那样工作。以下示例应实际演示这两种情况:

HomeController.cs

代码语言:javascript
复制
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

代码语言:javascript
复制
<!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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36776529

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档