Reputation: 111
I have a view which load values and captures user input values. The page has multiple submit type buttons, and each has different purpose. Each button sends values to different sets of tables in the database. For e.g.,
My query is to make a common form POST method for all the buttons.
My View is like:
@using (Html.BeginForm("CallAllocationSubmit", "Home", FormMethod.Post, new { id = "FrmCallAllocationSubmit", ReturnUrl = ViewBag.ReturnUrl }))
{
<table>
<tr>
<td>
<button class="btn btn-success btn-icon " type="submit" style="width:100px;" name="Allocate" >Allocate</button>
</td>
<td>
<button class="btn btn-primary btn-icon " type="submit" style="width:100px;" name="Defer" >Defer </button>
</td>
</tr>
</table>
}
My Controller is like :
[HttpPost]
public ActionResult CallAllocationSubmit(Allocation ObjAllocation, FormCollection frmCollection, string Allocate, string Defer)
{
try
{
if (!string.IsNullOrEmpty(Allocate))
{
// All code goes here
}
if (!string.IsNullOrEmpty(Defer))
{
// All Code goes here
}
return RedirectToAction("CallAllocation");
}
//catch block
}
I tried above method using if condition but the buttons ain't working, and not coming to the controller on clicking. Please suggest how can I implement this functionality, or provide correction for my view and controller. Thanks!
Upvotes: 0
Views: 150
Reputation: 111
I would use ENUM for multiple buttons instead string actions, because you get intellisense that way:
public enum FilterButton{
Allocate = 1,
Defer = 2, //...
};
public ActionResult CallAllocationSubmit(Allocation ObjAllocation,FormCollection frmCollection, FilterButton buttonAction)
{
if(buttonAction == FilterButton.Allocate){
//...code
}
}
in View:
<button type="submit" name="buttonAction" value="@FilterButton.Allocate" ></button>
Upvotes: 0
Reputation: 1396
For your scenario, you can use command parameter in your post action
That is,
<button class="btn btn-success btn-icon " type="submit" style="width:100px;" name="command" value="Allocate">Allocate</button>
set the name for all buttons
as command and set value as your button action.
Now in your post action method, use string command
as a parameter
[HttpPost]
public ActionResult CallAllocationSubmit(Allocation ObjAllocation, FormCollection frmCollection, string command)
{
try
{
if (command = "Allocate"))
{
// code for Allocate action
}
if (command = "Defer"))
{
// code for Defer action
}
return RedirectToAction("CallAllocation");
}
//catch block
}
Upvotes: 1
Reputation: 784
Give the submit buttons the same name (not id) E.g. mySubmitButton. Set the value of each button to the value to retrieve (E.g. value="Allocate") Then in the controller use
public ActionResult CallAllocationSubmit(Allocation ObjAllocation, FormCollection frmCollection, string mysubmitButton)
Upvotes: 0