如果操作按钮和表单字段位于不同的部分,该怎么办?

时间:2012-12-14 08:52:24

标签: asp.net-mvc asp.net-mvc-3 razor

假设我们有一个编辑表单来创建新用户。现在,保存按钮被放置在页脚的不同部分。

我的问题是我无法在一个表单中获取编辑字段和保存按钮,因为该按钮位于不同的部分。

因此,我无法提交表格。

解决此问题的最佳方法是什么?

_Layout.cshtml

<div class="content">
    @RenderBody()
</div>
<div class="footer">
    @RenderSection("Footer")
</div>

Index.cshtml

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@section Footer
{
    <input type="submit" value="Save" />
}

@using(Html.BeginForm())
{
    <h2>New User</h2>
    @Html.EditorForModel()
}

3 个答案:

答案 0 :(得分:2)

您可以明确地调用form.Dispose(),而不是using语句:

@{ var form = Html.BeginForm() }

<h2>New User</h2>
@Html.EditorForModel()

@section Footer
{
    <input type="submit" value="Save" />
    @{ form.Dispose(); }
}

修改

但是你必须至少确保Body和Footer部分在同一个容器中,例如:

<div class="content">
    @RenderBody()
    <div class="footer">
        @RenderSection("Footer")
    </div>
</div>

使用问题中所写的布局,content div(以及form标记)必须在submit按钮出现之前关闭。这在逻辑上是行不通的:

<div class="content">
    @RenderBody()               @@ form opens, and therefore must close here
</div>
<div class="footer">
    @RenderSection("Footer")    @@ submit button is here -- can never be inside the form
</div>

编辑旁边:将表单拆分为多个部分视图似乎是一个非常糟糕的主意。你可能会把它称为代码味道 - 如果可能的话,我会尽量避免它。

答案 1 :(得分:1)

你发现了一个非常尴尬的工作。我建议这样做:

  • 为了区分单击的不同按钮的操作,请在模型中创建新属性:public string Action { get; set; }
  • 为您提供表单ID,并为您的新模型属性添加隐藏的输入。
<form id="my-form">
    @Html.HiddenFor(x => x.Action)
    ...
</form>
  • 在页脚中创建具有相同类但不同值的按钮:
   
<button class="btn-submit" value="action1">Submit</button>
<button class="btn-submit" value="action2">Submit</button>
  • 使用以下JavaScript:
 
$('.btn-submit').live('click', function() {
    // update value of hidden input inside the form
    $('#Action').val($(this.val()));
    // submit the form
    $('#my-form').submit();
});
  • 在ActionResult中,根据Action属性的值执行不同的操作:
public ActionResult WahteverAction(WhateverModel model)
{
    if(ModelState.IsValid)
    {
        if(model.Action == "action1")
        {
            // do whatever needs to be done for action1
        }
        if(model.Action == "action2")
        {
            // do whatever needs to be done for action2
        }
    }
    return View();
}

答案 2 :(得分:0)

我找到了解决问题的方法。这不好,但它确实有效。

我用锚点替换了提交按钮。单击锚点时,将调用javascript函数。

<a name="save" onclick="submitAction(this)"></a>

javascript函数在表单中创建一个隐藏的提交按钮并单击它。

function submitAction(sender) {
    var action = $(sender).attr('name');
    $('form').append('<input type="submit" style="display:none" id="tmpSubmit" />');
    $('#tmpSubmit').attr('name', action);
    $('#tmpSubmit').click();
}