【问题标题】:Posting form elements with jQuery in ASP.NET MVC not working在 ASP.NET MVC 中使用 jQuery 发布表单元素不起作用
【发布时间】:2013-03-07 02:02:29
【问题描述】:

我正在使用ASP.NET MVCjQuery

我有一个文本框和一个包含数据的 HTML 表格,例如:

<form action="/Server/Test" method="post">

     <input type="text" id="ServiceAccount" />

     <table>
          <tr>
               <th>Heading 1</th>
               <th>Heading 2</th>
          </tr>
          <tr>
               <td>Cell data 1</td>
               <td>Cell data 2</td>
          </tr>
     </table>

</form>

上表未绑定到视图模型,它通过 AJAX/JSON 填充。

我需要将文本框的值和单元格数据发布到控制器的操作方法中。因此,如果我在文本框中输入 1234567,那么我需要将此值与表的内容一起发布到操作方法。我还需要表格数据进行处理。这可能吗?我找不到样品。

我的操作方法如下所示:

[HttpPost]
public ActionResult Test(string[] data)
{
     // Use the value Cell data 1
     // Use the value Cell data 2

     return View();
}

鉴于我下面的代码它没有达到我的操作方法:

$('form').submit(function () {
     $.post('@Url.Action("Test", "Server")', $('form').serialize(), function (data) {
          alert('success');
     });
     return false;
});

我不明白我做错了什么。

【问题讨论】:

  • 你的路由配置是什么样的?
  • 它只是具有启动 MVC 项目时的默认配置。
  • 存在 javascript 错误或路由问题。如果您在浏览器中打开调试控制台,您是否看到任何 JS 错误?如果您打开网络选项卡,您会收到 404 吗?
  • 您还需要在输入字段上设置名称属性,并将操作方法​​的参数名称设置为相同的名称。将类型从字符串数组更改为字符串。
  • 您不能将名称属性添加到表中。

标签: javascript jquery asp.net html asp.net-mvc


【解决方案1】:

I need the value of the textbox and the cell data to be posted to my controller's action method. So if I typed in 1234567 in the textbox then I need this value posted to the action method together with the contents of the table. I need the table data also for processing. Is this possible? I can't find a sample.

是的,这是可能的,但是您的表必须包含隐藏输入,trtd 数据不能通过提交发送(正常提交,不是 ajax),serialize() 也不要序列化表行。看这个问题:

How to submit a table with dynamic rows of data via asp.net mvc or jquery?

【讨论】:

  • 谢谢。我查看了代码,它提到了输入类型。这与表格有何关系?请问您有一些示例工作代码吗?
  • @BrendanVogt 正如您所写,您想提交表格内容,只需使用 jquery 在td 标签中添加具有相同数据的隐藏输入。主要思想是创建正确的名称,这些名称将绑定在服务器端。如何做到这一点,您可以在我的链接中的文章中看到。
【解决方案2】:

基本上,当您提交表单时,只提交 INPUT、Hidden、TextAra 等表单元素,而不提交 div、table、span 等。

因此,如果您想提交表格数据,请使用隐藏字段。

或者更好的方法是循环表格数据,准备 JSON 并将其作为参数发布。

$('form').submit(function () {

     var myPostData=//construct this from table and convert as JSON
     $.post('@Url.Action("Test", "Server")', {data:myPostData}, function (resp) {
          alert('success');
     });
     return false;
});

【讨论】:

    【解决方案3】:

    在您的控制器操作方法中设置WebMethod 对于

    [WebMethod]
    [HttpPost]
    public ActionResult Test(string[] data)
    {
         // Use the value Cell data 1
         // Use the value Cell data 2
    
         return View();
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-24
      • 2013-01-09
      • 2013-04-21
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 2011-01-15
      相关资源
      最近更新 更多