【问题标题】:MVC 4 \ form submit button not working when view is using master layout当视图使用主布局时,MVC 4 \ 表单提交按钮不起作用
【发布时间】:2013-10-08 20:09:15
【问题描述】:

好的,after long investigation,似乎当我创建了一个与 _layout.cshtml 一起使用的视图时 - 我拥有的表单中的提交按钮不起作用(没有操作返回给控制器)​​。

仅当我创建视图并取消选中“使用布局或母版页”时 - 按钮才有效!

这似乎非常不清楚,所以 - 我如何才能同时查看通用 _layout.cshtml 和 working form button

以下: 尝试在 MVC4 (+Razor) 中实现一个表单

控制器(应该获得发布操作):

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; }
    }

【问题讨论】:

  • 放上你的代码,看看有什么问题

标签: forms asp.net-mvc-4 controller


【解决方案1】:

你应该删除你的内部表单标签,

@using (Html.BeginForm("SearchResults", "General", FormMethod.Post))

将为您生成一个表单标签。

此外,您应该使用 html 助手来生成表单元素:

@Html.LabelFor(model => model.Property1)
@Html.TextBoxFor(model => model.Property1)

因此可能是模型绑定问题。 提交按钮属于您的嵌套内部表单,这里没有正在提交的模型。

@model MvcApplication2.Models.SearchParamsModel

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm("SearchResults", "General", FormMethod.Post))
   <section class="form-field">
      @Html.LabelFor(model => model.Property1)
      @Html.TextBoxFor(model => model.Property1)
      <input type="submit" value="some value" class="submit btn blue-btn special-submit" />
   </section>
}

【讨论】:

  • 谢谢!我完全按照你的建议做了,而且效果很好!所以,不需要在表格上声明
【解决方案2】:

我遇到了类似的问题,但不是你上面描述的问题,这样解决的:

我的“MVC 4 布局页面”在布局文档中有“表单”标签。另一方面,我的视图连接到布局页面(视图页面也有“使用(Html.BeginForm()){...}”)

因此,从布局页面中删除“form”标签应该可以做到,“因为使用 (Html.BeginForm()){...}”) 从视图页面中不再嵌套。

【讨论】:

    【解决方案3】:

    您在嵌套的Form 中声明提交按钮,而输入Property1 不是该表单的后代。将输入元素移动到嵌套表单中或完全移除嵌套表单

    编辑:您的嵌套表单元素也未指定操作,因此如果 General/SearchResults 不是此视图的默认值,您将无法获得预期结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      • 2018-03-09
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-10
      相关资源
      最近更新 更多