【问题标题】:Getting values from the html to the controller从 html 获取值到控制器
【发布时间】:2011-06-04 02:38:09
【问题描述】:

我正在尝试从我的控制器访问用户在表中引入的值。

这个表不是模型的一部分,视图源代码是这样的:

<table id="tableSeriales" summary="Seriales" class="servicesT" cellspacing="0" style="width: 100%">
    <tr>
        <td class="servHd">Seriales</td>
    </tr>
    <tr id="t0">
        <td class="servBodL">
            <input id="0" type="text" value="1234" onkeypress = "return handleKeyPress(event, this.id);"/>
            <input id="1" type="text" value="578" onkeypress = "return handleKeyPress(event, this.id);"/>
            .
            .
            .
        </td>
    </tr>
</table>

如何从控制器获取这些值(1234、578)?

接收表单集合不起作用,因为它没有获取表格...

谢谢。

【问题讨论】:

  • 表单集合应该接收输入控件值,您可能在使用数字作为 ID 时遇到问题。尝试使用 id="control1" 等。

标签: asp.net controller formcollection


【解决方案1】:

除非您的表格不在&lt;form&gt; 标签内,否则使用FormCollection 应该可以工作


在 Lazarus 的评论之上,你可以试试这个,但你必须为每个设置 name 属性:

<input id="seriales[0]" name="seriales[0]" type="text" value="1234" onkeypress="return handleKeyPress(event, this.id);"/>
<input id="seriales[1]" name="seriales[1]" type="text" value="578" onkeypress="return handleKeyPress(event, this.id);"/>

现在在你的 Action 方法中,你可以让你的方法看起来像这样:

[HttpPost]
public ActionResult MyMethod(IList<int> seriales)
{
    // seriales.Count() == 2
    // seriales[0] == 1234
    // seriales[1] == 578
    return View();
}

seriales 将被连接到这些值。

【讨论】:

    【解决方案2】:

    第一个选项: 使用 FormCollection 是访问动态数据的最简单方法。奇怪的是你不能从中得到这些值,你能检查一下吗?

    1. 是表里面的 元素?
    2. 能否添加名称属性 输入元素?注意 表单项受其名称约束, 不是身份证。

    第二个选项: 第二个选项是在模型中添加一个集合,并相应地命名所有内容。即

    public class MyModel
    {
      ...
      public IList<string> MyTableItems { get; set; }
    }
    

    在您看来,请使用以下名称:

    <input name="MyTableItems[]" value="" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多