Which one is better or both are same?

69 views Asked by At

I have a form which has 2 buttons "Delete" and "Edit".. on Post to check which button submitted the request... which of the 2 approaches is better and is there is any difference or both are same?

@if(isPost){
   if(!Request["buttonDelete"].IsEmpty()){
          //Do something
   }
  if(Request["btn"].Equals("buttonDelete")){
    //do something
  }
}
2

There are 2 answers

0
Vishal Sharma On BEST ANSWER

lets say you have html like this

<form method="post">
    <input type="text" name="txtName" value="Vishal" />
    <input type="submit" name="btnEdit" value="Edit" />
    <input type="submit" name="btnDelete" value="Delete" />
</form>

here two buttons are there having edit and delete action. now when you submit a form on a server side you can have clicked element under form collection paramerters that you can access like

Request.Params["btnDelete"]
Request.Params["btnEdit"]

whichever element is clicked , the other element will be null

   Request.Params["btnEdit"] will become null when you click on Delete button
same way Request.Params["btnDelete"] will become null when you click on Edit button

you can check like

if (!string.IsNullOrEmpty(Request.QueryString["Edit"]))
{
 // do edit                       
}

hope that helps ! :)

2
Ivan On

If this is ASP MVC then both of this approaches are not correct. You must have separated actions for Save and Edit:

public ActionResult Edit(Entity item){
    // do stuff
    return RedirectToAction('Index', new { lastAction = 'Edit' });
}

public ActionResult Save(Entity item){
    // do stuff
    return RedirectToAction('Index', new { lastAction = 'Delete' });
}

Then, on Index view you may check 'lastAction' parameter:

@{
  if(!Request.Params["lastAction"] == "Delete"){
    //do something
  } else if(Request["lastAction"] == "Edit"){
    //do something
  }
}