user1520494
user1520494

Reputation: 1184

Get Button Id on the controller using Ajax.BeginForm

The Objective:

I have a post with an Ajax.BeginForm and my objective is to get The Button Id on the controller. I've seen examples using Html.BeginForm, But I need an Ajax form,

The Code: C# MVC3

View:

@using (Ajax.BeginForm("Save", "Valoration", new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "HvmDetailTabStrip", OnSuccess = "OnSuccessSaveValoration" }))
{ 
    <div id ="HvmDetailTabStrip">
        @(Html.Partial("_ValorationDetail"))
    </div>
    <button type="submit" style="display:none" id="db1"></button>       
    <button type="submit" style="display:none" id="db2"></button>       
}        

Controller:

[HttpPost]
public ActionResult Save(ValorationModel model)
{
    if ("db1")    
    {
        var result = ValorationService.Save(ValorationModel);
    }
    else
    {
        // ....
    }         

    return PartialView("_ValorationDetail", ValorationModel);
}

Upvotes: 0

Views: 1819

Answers (1)

Evgenia
Evgenia

Reputation: 86

You can get your buttons' values like this:

@using (Ajax.BeginForm("Save", "Valoration", new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "HvmDetailTabStrip", OnSuccess = "OnSuccessSaveValoration" }))
    { 
        <div id ="HvmDetailTabStrip">
                @(Html.Partial("_ValorationDetail"))
        </div>
        <button type="submit" name="submitButton" value="db1"></button>       
        <button type="submit" name="submitButton" value="db2"></button>       
    }

And in your controller you can write:

[HttpPost]
    public ActionResult Save(ValorationModel model)
    {
       string buttonValue = Request["submitButton"];

       if(buttonValue == "db1"){
        var result = ValorationService.Save(ValorationModel);
       }else
       {
          ....
       }         

        return PartialView("_ValorationDetail", ValorationModel);
    }

Or if count of parameters you pass in method doesn't matter, you can use this:

[HttpPost]
        public ActionResult Save(ValorationModel model, string submitButton)
        {
           if(submitButton == "db1"){
            var result = ValorationService.Save(ValorationModel);
           }else
           {
              ....
           }         

            return PartialView("_ValorationDetail", ValorationModel);
        }

Other way how you can solve your problem is here ASP.Net MVC - Submit buttons with same value

Upvotes: 3

Related Questions