我们可以在httpsost上识别mvc中按钮的id

时间:2014-02-06 07:02:09

标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-areas

我有一个视图,它有两个提交按钮(保存和关闭,保存和新)。

 <span>
    <input type="button" value="Save&New" name="Save&New" id="SaveNew" />
    </span>
    <span>
    <input type="button" value="Save&Close" name="Save&Close" id="SaveClose" />
    </span>
    <span>

当我点击这些按钮中的任何一个时,模型数据会进入控制器并点击后期操作

    [HttpPost]
    public ActionResult Company(MyProject.Models.Company company)
    {
        return View();
    }

现在我的公司对象有完整的模型数据(例如company.phonenumber,company.state等)。 现在我想确定用户点击按钮的ID(保存和新建或保存和关闭)。 两个按钮点击导致相同的ActionResult(公司),我只想确定从哪个按钮点击请求来。 不能使用@ Html.ActionLink而不是input type = submit。 需要使用Jquery知道Id。

1 个答案:

答案 0 :(得分:6)

为您的按钮指定相同的名称:

<button type="submit" name="btn" value="save_new" id="SaveNew">Save&amp;New</button>
<button type="submit" name="btn" value="save_close" id="SaveClose">Save&amp;Close</button>

然后您的控制器操作可以使用此btn字符串参数。

[HttpPost]
public ActionResult Company(MyProject.Models.Company company, string btn)
{
    if (btn == "save_new")
    {
        // the form was submitted using the Save&New button
    }
    else if (btn == "save_close")
    {
        // the form was submitted using the Save&Close button
    }
    else
    {
        // the form was submitted using javascript or the user simply
        // pressed the Enter key while being inside some of the input fields
    }

    return View();
}

另请注意,我使用了submit按钮(type="submit"),而在您的示例中,您使用了不允许提交html表单的简单按钮(type="button")。