How to create Alert confrim Yes/No with MvcHtmlString in MVC C#

622 views Asked by At

The following code displays a warninng via MvcHtmlString.

in C#

public static MvcHtmlString ShowAlert(this HtmlHelper helper, string message)
{
     StringBuilder sb = new StringBuilder();

     sb.Append(@"$.confirm({" +
                      "title: false," +
                      "content: '" + message + "'," +
                      "type: 'dark'," +
                      "boxWidth: '45%'," +
                      "animation: 'RotateY',closeAnimation: 'RotateY',rtl: true," +
                      "typeAnimated: true," +
                      "buttons:" +
                      "{Close: {" +
                      "btnClass: 'btn-blue'} }});");

     return MvcHtmlString.Create(sb.ToString());
}

in Script

<script type="text/javascript">
        $('#bSubmit').click(event,
            function() {
                event.preventDefault();
                @Html.ShowAlert("Test");
            });
</script>

enter image description here

I want to display an Alert in MvcHtmlString which is Yes/No and returns the clicked buttons so I can use the value in the script.

2

There are 2 answers

1
Martin Staufcik On BEST ANSWER

You could create a javascript library of common functions in your application and include the confirm dialog into it. This way you could use the return value of the confirm dialog in the script as a callback.

site.js:

function showConfirm(message, clickCallback) {
    $.confirm({
        title: false,
        content: message,
        type: 'dark',
        boxWidth: '45%',
        animation: 'RotateY',
        closeAnimation: 'RotateY', 
        rtl: true,
        typeAnimated: true,
        buttons: { 
            Close: function () {
                clickCallback("Close");
            }
        } 
    });
}

Names of the buttons could be put into the function as another parameter, for example:

function showConfirmWithMultipleButtons(message, buttons /* array of names */, clickCallback)

Usage:

showConfirm('Simple confirm message', function(buttonName) {
    $.alert(buttonName);
});
1
thepanch On

I suggest you to use alertify https://alertifyjs.com/, it has it's own functions to create what you are asking, it would easy to use, you'll just need to write a new MvcHtmlString that writes this:

alertify.confirm('Confirm Title', 'Confirm Message', function(){ alertify.success('Ok') }
                , function(){ alertify.error('Cancel')});

you can find examples and documentation on the given link