Jaggu
Jaggu

Reputation: 6428

Save and cancel button posting the form

I am having 2 buttons namely Save and Cancel on my Profile.cshtml. Now my method is something like:

[HttpPost]
public ActionResult Profile()
{
  //code..
}

This save the records into database. But problem is because Cancel also posts here, the record is saved in database anyway. How do I handle this?

Upvotes: 1

Views: 3288

Answers (4)

Jason Evans
Jason Evans

Reputation: 29186

I often use a viewmodel class passed to a view, and in that viewmodel I have:

public string submit { get; set; }

public bool SaveButtonClicked()
{
    return this.submit.Equals("save");
}

public bool CancelButtonClicked()
{
    return this.submit.Equals("cancel");
}

Then in the controller

[HttpPost]
public ActionResult Save(MyViewModel inputViewModel)
{
    if(inputViewModel.SaveButtonClicked()) {}

   blah.......

}

My view looks like this

@using (Html.BeginForm())
{

   // Other stuff.
   <input type="submit" name="submit" value="Save" />
   <input type="submit" name="submit" value="Cancel" />
}

This works really well for me. By having the submit buttons use the same name, when either one is pressed, that name is passed to the submit property of the viewmodel. Not sure if having duplicate names is a bad idea, but for my needs it's fine.

Upvotes: 1

Dangerous
Dangerous

Reputation: 4909

In the view you could have 2 forms (one for each button), where the action of each form posts to the relevant action method in the controller. For example, in the view:

@using (Html.BeginForm("Save", "Profile"))
{
   <input type="submit" value="Save"/>
}

@using (Html.BeginForm("Cancel", "Profile"))
{
   <input type="submit" value="Cancel"/>
}

Then in the controller:

[HttpPost]
public ActionResult Save()
{
   ...
}

[HttpPost]
public ActionResult Cancel()
{
   ...
}

Upvotes: 2

Random Dev
Random Dev

Reputation: 52280

normaly you have the Save-button to submit your form and the cancel-"button" is just an ActionLink pointing back to your index or whatever.

Upvotes: 1

JakeJ
JakeJ

Reputation: 1381

This sounds like your cancel button has the type attribute set to submit. This will make the form submit as though you were pressing a save button.

The question you should ask yourself is what do you want the 'Cancel' button to do? It may be better to make a button that goes to another page if it's just a case of not finishing the form, otherwise if you need to point it towards an ActionResult then you will have to do a redirect for that to work.

Feel free to ask any questions if you need.

Upvotes: 0

Related Questions