user6656728
user6656728

Reputation:

identify which button is being clicked in mvc 5

I am creating a web app using mvc 5 here i have two buttons

<div class="row">
    <div class="col-sm-offset-5 col-sm-1">
        <input type="submit" name="save" value="SAVE" class="btn btn-primary glyphicon glyphicon-save" />
    </div>
    <div class="col-sm-offset-0 col-sm-1">

            <input type="submit" name="reset" id="reset" value="Reset" class="btn btn-warning active glyphicon glyphicon-refresh" />
    </div>                        
</div>

and i have a method which is being called after button click,

now on that event i want to differentiate the button click,

like,

if a user click

<input type="submit" name="save" value="SAVE" class="btn btn-primary glyphicon glyphicon-save" />

then

{
//this code should run
}

and if a user clicks

<input type="submit" name="reset" id="reset" value="Reset" class="btn btn-warning active glyphicon glyphicon-refresh" />

then

{ //this set of code should run }

and my method looks like this

[HttpPost]
        public ActionResult insertrecd(FormCollection fc)
        { 
            if(fc["reset"]==null)
            {
                return RedirectToAction("party", "party");
            }
            else
            {
                ViewBag.message = string.Format("Hello {0}.\\nCurrent Date and Time: {1}", "name", DateTime.Now.ToString());
                return RedirectToAction("party", "party");
            }
        }

what i need to do, i want to do different code on different button clicks?

Upvotes: 0

Views: 1813

Answers (1)

Alex
Alex

Reputation: 38509

Give each input button the same name, but a different value

<input type="submit" name="action" value="save" class="btn btn-primary glyphicon glyphicon-save" />

<input type="submit" name="action" id="reset" value="reset" class="btn btn-warning active glyphicon glyphicon-refresh" />

The value will then be in your form collection as

fc["action"]

So your controller action could look like

[HttpPost]
public ActionResult insertrecd(FormCollection fc)
{
    var action = fc["action"];

    if(action == "save")
    {
        //save stuff
    }

    if(action =="reset")
    {
        //reset stuff
    }
}

Upvotes: 3

Related Questions