【问题标题】:Input type='image' as submit button behaves differently than 'submit'输入 type='image' 作为提交按钮的行为与 'submit' 不同
【发布时间】:2018-12-20 22:56:59
【问题描述】:

我有多个按钮提交表单。我检查传入控制器的输入值单击了哪个按钮。

public async Task<ActionResult> MyAction(MyModel model, string command)

下面的 html 有效。在我的控制器中command 等于myValue

<input type="submit" name="command" value="myValue" />

下面的 html 不起作用。在我的控制器中commandnull

<input type="image" name="command" src="..." value="myValue"/>

W3C says the type 'image' is a submit button

那么为什么这两个输入元素的行为不同呢?

【问题讨论】:

  • Afaik value 不适用于图像提交按钮,至少在 FF 中是这样。可悲的是 W3C 与现实不一样

标签: asp.net-mvc html asp.net-mvc-5


【解决方案1】:

根据问题中链接到的过期工作草案、当前 HTML5 CR 草案和 HTML 4.01 建议,图像提交按钮的行为确实不同,根据定义。根据 HTML5 CR,construction of the form data set 不会为图像提交按钮添加 name=value 对,而是将 name.x=... 和 name.y=... 以单击位置的坐标作为值。这对应于旧定义和浏览器实践,除了 Chrome 另外添加了一个名称=值对。

因此,在您的情况下,表单数据将包含字段command.xcommand.y,以及您可能不感兴趣的值。这是您在编写表单处理程序时需要作为起点的内容。这意味着如果您需要识别使用了几个图像按钮中的哪一个,您需要为它们赋予不同的name 属性。

【讨论】:

  • 非常深入的解释。解释这一点的句子位于链接的第 3.3 部分
  • 对不起,但是...这似乎没有提供任何有效的答案,它不包括有效的代码。它解释了为什么 OP 代码不起作用,不幸的是,您提供的 SUBTLE 解决方案对我不起作用。还是你想说这是不可能的?
【解决方案2】:

您可以有一个隐藏字段,并在该隐藏字段中设置命令名称,无论单击哪个按钮,都可以获取在服务器端提交表单的按钮的名称。

Javascript

$(".submit").click(function(){
    var commandName = $(this).attr("val");
    $("input[type=hidden]").val(commandName);
});

HTML

<form>
    <input type="hidden" name="command">

    <input type="submit" value="submitbtn" class="submit" />
    <input type="image" src="..." value="imagebtn" class="submit"/>
</form>

【讨论】:

  • 这在基本功能方面不必要地依赖于客户端脚本。禁用脚本后,页面将无法按预期方式工作。
  • @JukkaK.Korpela Asp.net webform 应用程序在内部使用了我上面提到的相同技术。检查asp.net web form application的html你会发现__EVENTTARGET, __EVENTARGUMENT
【解决方案3】:

完成这项任务的最简单(也许不安全)的方法是使用内联 JQuery,方法如下:

查看:

<input type="image" src="..." onclick="$('#hidImgValue').val('Image1');" />

<input type="hidden" id="hidImgValue" name="command" value="none" />

控制器:

public async Task<ActionResult> MyAction(MyModel model, string command)

Command var 将有 "Image1" 作为值。

【讨论】:

    猜你喜欢
    • 2011-10-20
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多