我的 ASP.NET MVC 3 网站在服务器端有代码检查提交表单时单击的提交按钮的名称。当我使用鼠标单击按钮时代码有效,但是当我使用 Enter 键时,表单已发布,但请求不包含提交按钮的名称。
我可以在提交按钮上设置一些属性来让它在单击和使用 Enter 键时都起作用吗?
这是我的 HTML:
<div>Search:</div>
<form action="/Item/Search" method="post">
<input class="fulltextsearch" id="FTSearchText" name="FTSearchText" type="text" value="" />
<input type="submit" value="Go" name="FTSearchButton" />
</form>
</div>
在服务器端,我有一个自定义模型 Binder ,它使用以下代码来确定用户是否单击了提交按钮。
// See if the value provider has the required prefix
var hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName);
var searchPrefix = (hasPrefix) ? bindingContext.ModelName + "." : string.Empty;
var searchButton = GetValue(bindingContext, searchPrefix, "FTSearchButton");
// If this value doesn't have value, the user didn't click the button so exit
if (string.IsNullOrEmpty(searchButton)) {
return null;
}
private static string GetValue(ModelBindingContext context, string prefix, string key) {
var result = context.ValueProvider.GetValue(prefix + key);
return result == null ? null : result.AttemptedValue;
}
这是我遇到的问题。我有一个显示项目列表的页面。我在 HTML 表单中有一个“搜索”文本框和一个提交按钮。当用户在文本框中输入文本并单击搜索按钮或使用回车键时,页面通过 HTML 发布表单数据 GET , 并返回找到的前八条记录。该页面然后显示其他页面的页面链接。问题是,当用户单击页面链接时,表单数据全是空白,我的过滤器信息也丢失了(使用这些链接时,表单没有发布表单值)。因此,我最终显示了一个空白的项目列表(空白搜索返回零结果),而不是对数据进行分页。
通过在我的表单数据中添加对按钮名称的检查,我可以确定是简单地分页数据,还是重新查找。
最佳答案
我不会依赖这个。这种情况下有很多记录在案的错误。只需使用 name='submit'
添加一个隐藏字段。这样就不会太难重新编码后端。
<input type='hidden' name='submit' value='FTSearchButton'/>
关于使用 Enter 键时,HTML 表单不包含表单提交按钮名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8582606/