MVC 4表单 - 提交按钮无法正常工作

3
尝试在MVC4(+ Razor)中实现表单,但提交按钮没有任何作用。
控制器(应该获取POST操作):
public class GeneralController
{
    [HttpPost]
    public ActionResult SearchResults(SearchParamsModel searchParams)
    {
        // doin some stuff here
        return View("SearchResultsView");
    }
}

查看 (.cshtml)

@model Models.SearchParamsModel 
@using (Html.BeginForm("SearchResults", "General", FormMethod.Post))
{
    <section class="form-field">
        <input type="text" name="Property1" id="Property1" class="field field139 autocomplete-init-no-img" />
        <label for="Property1">value1</label>

        <form action="" method="post" class="clearfix">           
            <input type="submit" value="some value" class="submit btn blue-btn special-submit" />
        </form>
    </section>
}

模型

public class SearchParamsModel 
{
    public string Property1{ get; set; }
}

3
不要创建嵌套表单(Nested Forms)... - Erik Philips
刚刚帮我了!谢谢! - Yisroel M. Olewski
3个回答

5
如果您只需要实现搜索功能,无需使用ViewModel,可以通过发送带有搜索请求的字符串来实现。而且它不应该是Post方法。
public ActionResult SearchResults(string searchString)
{
    //code for searching

    return View(yourmodel);
}

在视图中

@using (Html.BeginForm())
{     
    Searching: @Html.TextBox("SearchString")
    <input type="submit" value="Search"/>
}

谢谢,我会尝试的。然而,我希望我的代码整洁,我的搜索有多个输入参数,不想使用纯字符串来维护搜索。 - user1025852
谢谢,我按照你的建议做了。但是还是不起作用。只有在我的.cshtml文件的开头添加@{ Layout = null }才行(为了简化事情,假设我有一个没有字段的按钮,并且我想到达控制器)。 - user1025852

2

Html.BeginForm助手将为您创建表单标记,请尝试使用它...

视图:

@model Models.SearchParamsModel 

@using (Html.BeginForm("SearchResults", "General", FormMethod.Post))
 {
  <section class="form-field">
    <input type="text" name="Property1" id="Property1" class="field
                  field139 autocomplete-init-no-img" />
    <label for="Property1">value1</label>
    <input type="submit" value="some value" 
                    class="submit btn blue-btn special-submit" />   
  </section>
 }

你有两个嵌套的表单,所以提交按钮只适用于内部表单。你从未提交外部表单。外部表单是使用Html.BeginForm助手创建的,但从未触发。 - German Blanco
谢谢。Html.BeginForm 应该准确地放在 <section class="form-field"> 的顶部吗?无论如何,它似乎没有起作用...这里可能仍然缺少一些东西。 - user1025852
控制器是否已触发?如果是这样,请编辑您的控制器,使用FormCollection按名称提取表单值,如此处所示https://dev59.com/3Ww05IYBdhLWcg3w11Qk#16822103 - German Blanco
不,控制器没有被触发。首先我想调试调用(之后我会处理呈现结果的问题...) - user1025852

1
如果我在MVC 4或5中执行相同操作,将得到相同的结果。
请尝试在所有控件周围添加
标签。
@using (Html.BeginForm("SearchResults", "General", FormMethod.Post))
{
  <fieldset>
  // your controls...
  <input type="text" name="Property1" id="Property1" class="field field139 autocomplete-init-no-img" />
  <label for="Property1">value1</label>
  <input type="submit" value="some value" class="submit btn blue-btn special-submit" />      
  // if you need a partial form included:
  @{Html.RenderPartial("_SomeOtherPartial", @Model);}
  // etc..
  </fieldset>
}

试一试...

告诉我


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接