Search results

Prevent the focus on the first element in ASP.NET MVC Dialog control

20 Apr 2021 / 1 minute to read

By default, the dialog focuses on the first elements of the content area which can be active and focusable. You can prevent this default focusing behavior using the Open event and by enabling the preventFocus argument.

Bind the open event and enable the preventFocus argument within an event like the below example.

razor
controller.cs
Copied to clipboard
<div id="container" style="height:400px;">
    @Html.EJS().Button("targetButton").Content("Open Dialog").Render()
    @Html.EJS().Dialog("dialog").Header("Sign In").Open("onOpen").ContentTemplate(@<div class='wrap'>
    <div class='form-group'><label for='email'>Email:</label>
        <input type='email' class='form-control' id='email'>
    </div>
    <div class='form-group'>
        <label for='comment'>Password:</label>
        <input type='password' class='form-control' id='password'>
    </div></div>).Target("#container").Width("300px").Buttons(btn=> {
        btn.Click("dlgButtonClick").ButtonModel(ViewBag.DialogButtons1).Add();
        btn.Click("dlgButtonClick").ButtonModel(ViewBag.DialogButtons2).Add();}).Render()
</div>
<script>
    document.getElementById('targetButton').onclick = function () {
        var dialog = document.getElementById("dialog").ej2_instances[0];
        dialog.show();
    }
    function dlgButtonClick() {
        var dialogObj = document.getElementById('dialog').ej2_instances[0];
        dialogObj.hide();
    }
    function onOpen() {
        args.preventFocus = true;
    }
</script>
Copied to clipboard
public class HomeController : Controller
{

    public class ButtonModel
    {
        public string content { get; set; }
        public bool isPrimary { get; set; }

    }

    public ActionResult Index()
    {
        ViewBag.DialogButtons1 = new ButtonModel() { isPrimary = true, content = "Ok" };
        ViewBag.DialogButtons2 = new ButtonModel() { content = "Cancel" };
        return View();
    }

}