从脚本

时间:2016-04-24 21:27:28

标签: javascript jquery asp.net asp.net-mvc twitter-bootstrap

假设有一个带有多个输入按钮的.NET Bootstrap表单。当用户按下Enter键时,无论用户在哪个面板中修改数据,都会将默认按钮值发送到Controller。我认为代码确定哪个面板处于活动状态以及哪个按钮对应于该面板,但是如何将正确的面板按钮值发送给Controller? $ closestButton.Submit();没有工作,我找不到答案在这里搜索问题。提前谢谢!

控制器:

[HttpPost]
public ActionResult SaveData(SaveDataViewModel model, string buttonCommand)
{
    if (buttonCommand == "Save Basics")
    {
        //Do stuff
    }
    else if (buttonCommand == "Save Owner")
    {
        //Do other stuff
    }
    return View();
}

观点:

<div class="row">
    <div class="col-lg-12">
        <div class="panel panel-default" id="basicsPanel">
            <div class="panel-heading">Basic Info</div>
            <div class="panel-body">
                <div class="row">
                    <!-- Text boxes and such -->
                </div>
                <div class="row">
                    <!-- This is the default button upon pressing Enter key, and its value is always sent to the Controller -->
                    <button type="submit" id="saveBasics" name="buttonCommand" class="btn btn-success pull-right" value="Save Basics">Save Basics</button>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="row">
    <div class="col-lg-12">
        <div class="panel panel-info" id="ownerPanel">
            <div class="panel-heading">Owner</div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-lg-4">
                        <!-- Other text boxes and such -->
                    </div>
                </div>
                <div class="row">
                    <div class="col-lg-12 text-right">
                        <!-- This button should be the one used when a User presses the Enter key while filling in data in this panel -->
                        <button type="submit" id="saveOwner" name="buttonCommand" class="btn btn-success" value="Save Owner">Save Owner</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

最后,该脚本检测到按下了哪个按钮,但无法设置“buttonCommand”的值:

$(document).keypress(function (e) {
    if (e.which == 13) {
        var $activeElement = document.activeElement.id;
        var $closestPanel = $($activeElement).closest('panel');
        var $closestButton = $($closestPanel).children('input[type=submit]');
        //Got the intended button, now how to send its value?
    }
});

1 个答案:

答案 0 :(得分:0)

这里的答案是:a)捕获按键事件并测试它是否为Enter键; b)如果是,则调用函数以防止默认行为; c)获得活跃元素; d)获取最近面板的id属性; e)检查面板名称是否等于页面的一个面板名称,并在该面板的按钮ID上调用.click()。