1

I want to use sweet alert with asp.net core c#. To replace my alert system. However I need some guidance. When I am on a controller say edit and just after the save I want to excute this javascript what is my best way in .net core in web forms days we had registerscript.

I also need to show this message when I create a record

https://sweetalert2.github.io/

swal({
        title: "MIS",
        text: "Case Created your Case Number is ",
        icon: "warning",
        buttons: true,
        dangerMode: true,
    })

2 Answers 2

3

1.If you want to alert after save successfully,follow this:

Model:

public class Test
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Index.cshtml:

@model IEnumerable<Test>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                    <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                    <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>
@section Scripts
{
    @if (TempData["notification"] != null)
    {
        @Html.Raw(TempData["notification"])
    }
}

Edit.cshtml:

@model Test
<h4>Test</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form asp-action="Edit">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Id" />
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

Controller:

public class TestsController : Controller
{
    private readonly Mvc3_1Context _context;

    public TestsController(Mvc3_1Context context)
    {
        _context = context;
    }

    public void Alert(int id)
    {
        var msg = "<script language='javascript'>swal({title: 'MIS',text: 'Case Created your Case Number is "+id+"', icon: 'warning',buttons: true,dangerMode: true})" + "</script>";
        TempData["notification"] = msg;
    }

    // GET: Tests
    public async Task<IActionResult> Index()
    {
        return View(await _context.Test.ToListAsync());
    }
    // GET: Tests/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var test = await _context.Test.FindAsync(id);
        if (test == null)
        {
            return NotFound();
        }
        return View(test);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, Test test)
    {
        if (id != test.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            _context.Update(test);
            await _context.SaveChangesAsync(); 

            Alert(id);//add this method

            return RedirectToAction(nameof(Index));
        }
        return View(test);
    }
}

_Layout.cshtml:

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>

//add this line
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>

Result: enter image description here


2.If you want to alert before save sucessfully:

Model:

Same as the option one.

Index.cshtml:

@model IEnumerable<Test>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.Name)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.Name)
                </td>
                <td>
                    <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                    <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                    <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
                </td>
            </tr>
        }
    </tbody>
</table>

Edit.cshtml:

@model Test
<h4>Test</h4>
<hr />
<div class="row">
    <div class="col-md-4">
        <form>
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Id" />
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="button" value="Save" class="btn btn-primary" onclick="confirmEdit()"/>
            </div>
        </form>
    </div>
</div>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
<script>
    function confirmEdit() {
        swal({
            title: "MIS",
            text: "Case Created your Case Number is " + $("#Id").val(),
            icon: "warning",
            buttons: true,
            dangerMode: true,
        }).then((willUpdate) => {
            if (willUpdate) {
                $.ajax({
                    url: "/tests/edit/"+$("#Id").val(),
                    type: "POST",
                    data: {
                        Id: $("#Id").val(),
                        Name:$("#Name").val()
                    },
                    dataType: "html",
                    success: function () {
                        swal("Done!", "It was succesfully edited!", "success")
                            .then((success) => {
                                window.location.href="/tests/index"
                            });
                        
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        swal("Error updating!", "Please try again", "error");
                    }
                });
            }
        });                       
    }
</script>
}

Controller:

    public class TestsController : Controller
{
    private readonly Mvc3_1Context _context;

    public TestsController(Mvc3_1Context context)
    {
        _context = context;
    }
    // GET: Tests
    public async Task<IActionResult> Index()
    {
        return View(await _context.Test.ToListAsync());
    }
    // GET: Tests/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var test = await _context.Test.FindAsync(id);
        if (test == null)
        {
            return NotFound();
        }
        return View(test);
    }

    [HttpPost]
    public async Task<IActionResult> Edit(int id, [FromForm]Test test)
    {
        if (id != test.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            _context.Update(test);
            await _context.SaveChangesAsync();              
            return RedirectToAction(nameof(Index));
        }
        return View(test);
    }
}

_Layout.cshtml:

Same as option one.

Result: enter image description here

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for taking the time apreciate it
How would one achieve this for the create command as well the intial save?
Hi @rogue39nin,did you want to apply sweet alert to create action?Which option is your requirement?
Hi Rena both is my requirment i will updated the question
As you see the answer is too long.Please post a new thread and share your sample.
|
1

I had to use AJAX on my .NETCORE 3.1 application to implement the Sweet Alert 2.

The syntax is just a little different than yours.

Documentation for Sweet Alert 2 can be found on this link.

A simple example, say you want an early on a button click, you could do something like:

HTML:

<input id="btnSubmit" type="button" class="btn btn-success btn-block" value="Submit" />

jQuery:

<script type="text/javascript">
    $(document).ready(function () {
        $("#btnSubmit").click(function () {
            Swal.fire({
                title: 'MIS',
                text: "Case Created your Case Number is",
                icon: 'error',
                confirmButtonText: 'Ok'
           })
        });
    });
</script>

Also, don't forget to add your sweetalert script tags:

<script src="~/filepath/sweetalert2.min.js"></script> 

1 Comment

that will not get the value of the case created Renna answer was more complete

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.