ASP.NET MVC模式BeginForm发送Null HtmlAttribute

时间:2014-09-29 11:00:46

标签: c# asp.net asp.net-mvc twitter-bootstrap

我正在使用Bootstrap Modal在数据库中创建一个新项目。

我有一个包含以下代码的页面。页面网址是... / ProjectManager / Projects / 1。

我想将这个id值(在url中)传递给我的模态,然后我需要在表单中使用它。当我运行此代码时,控制器方法参数id将为空。

 <a data-toggle="modal" class="btn btn-info" href="AddModule" data-target="#NewModule">New Module</a>

  <div class="modal fade" id="NewModule" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title text-left">Add New Module/Submodule</h4>
                </div>
                @using (Html.BeginForm("AddModule", "ProjectManager", FormMethod.Post, new { id = ViewContext.RouteData.Values["Id"].ToString() }))
                {
                    <div class="modal-body">
                        <div class="te">
                            <div class="form-horizontal">
                                @Html.ValidationSummary(true, "", new { @class = "text-danger" })


                                <div class="form-group">
                                    <div class="col-md-4">
                                        @Html.Label("Module Name", htmlAttributes: new { @class = "control-label col-md-2" })
                                    </div>
                                    <div class="col-md-8">
                                        @Html.Editor("ModuleName", new { htmlAttributes = new { @class = "form-control" } })
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <a href="#" class="btn" data-dismiss="modal">Close</a>
                        <button type="submit" class="btn btn-primary">Create Module</button>
                    </div>

                }
            </div>
        </div>
    </div>

这是我的控制器方法

    [HttpPost]
    public ActionResult AddModule(string ModuleName, string id)
    {

        return RedirectToAction("Projects");
    }

1 个答案:

答案 0 :(得分:0)

您正在使用BeginForm的错误重载。

您正在使用BeginForm(HtmlHelper, string, string, FormMethod, object)。您可以在MSDN上看到对象是htmlAttributes,因此这会设置表单元素的id

您需要使用BeginForm(HtmlHelper, string, string, object, FormMethod)。在此重载中,对象为routeValues,这是您想要的对象。

所以你需要交换参数:

@using (Html.BeginForm("AddModule", "ProjectManager",
    new { id = ViewContext.RouteData.Values["Id"].ToString() },
    FormMethod.Post))