How to create the confirm box in mvc controller?

user279stack1 picture user279stack1 · Mar 21, 2013 · Viewed 55.6k times · Source

I need to create the confirm box in mvc controller?. Using this 'yes' or 'no' value I need to perform the action in my controller. How we do that?

Sample code:

    public ActionResult ActionName(passing value)
        {
             // some code 
             message box here
               if (true)
                     { true code}
              else { else code}
       }

Answer

AliRıza Adıyahşi picture AliRıza Adıyahşi · Mar 21, 2013

You can do this with ActionLink

@Html.ActionLink(
    "Delete", 
    "DeleteAction", 
    "Product", 
    new { confirm = true, other_parameter = "some_more_parameter" }, 
    new { onclick = "return confirm('Do you really want to delete this product?')" })

If user confirm, then link parameter will pass to the controller action method.

public ActionResult DeleteAction(bool confirm, string other_parameter)
{
    // if user confirm to delete then this action will fire
    // and you can pass true value. If not, then it is already not confirmed.

    return View();
}

Update

You can not show message box in controller side. But you can do this like following

public ActionResult ActionName(passing value)
{
     // some code 
     message box here
     if (true){ ViewBag.Status = true }
     else { ViewBag.Status = false}

     return View();
}

And view

<script type="text/javascript">
function() {
    var status = '@ViewBag.Status';
    if (status) {
        alert("success");
    } else {
        alert("error");
    }
}
</script>

But these all codes are not elegant way. This is solution of your scenerio.