Ad

How To Create Alert Confrim Yes/No With MvcHtmlString In MVC C#

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.

Ad

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);
});
Ad
source: stackoverflow.com
Ad