Search code examples
asp.net-mvcasp.net-mvc-4asp.net-mvc-areas

can we identify the id of a button in mvc on httppost


I have a view which has two submit buttons(save&close,save&new).

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

When i hit any one of these buttons,the model data goes to controller and hits a post action

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

now my company object has complete model data(such as company.phonenumber,company.state etc etc). Now i want to identify the id of the button(either save&new or save&close) user clicked. Both buttons click leads to same ActionResult(Company) and i just want to identify from which button click the request came. Cannot use @Html.ActionLink instead of input type =submit. Need to know the Id with out using Jquery.


Solution

  • Give your buttons the same name:

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

    and then your controller action could take this btn string parameter.

    [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();
    }
    

    Also notice that I have used submit buttons (type="submit") whereas in your example you have used simple buttons (type="button") which do not allow for submitting an html form.