在ASP.NET Core C#之后使用JavaScript代码 [英] Using JavaScript code behind asp.net core c#

查看:226
本文介绍了在ASP.NET Core C#之后使用JavaScript代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将甜蜜警报与asp.net核心c#一起使用.更换我的警报系统.但是我需要一些指导.当我在控制器上说编辑时,在保存之后,我想对这个javascript进行讲解,这是我们拥有注册脚本的.net核心中Web表单中最好的方法是什么.

创建记录时,我还需要显示此消息


2.如果要在成功保存之前发出警报:

型号:

与选项一相同.

Index.cshtml:

  @model IEnumerable< Test>< table class ="table">< thead>< tr>< th>@ Html.DisplayNameFor(model => model.Name)</th>< th</th></tr></thead>< tbody>@foreach(模型中的var项){< tr>< td>@ Html.DisplayFor(modelItem => item.Name)</td>< td>< asp-action =编辑";asp-route-id ="@ item.Id">编辑</a>|< asp-action =详细信息";asp-route-id ="@ item.Id"> Details/a.|< asp-action =删除";asp-route-id ="@ item.Id"> Delete/a></td></tr>}</tbody></table> 

Edit.cshtml:

  @model测试< h4>测试</h4>< hr/>< div class ="row">< div class ="col-md-4">< form>< div asp-validation-summary =仅限模型"class ="text-danger"</div><输入类型=隐藏的".asp-for ="Id"/>< div class ="form-group">< label asp-for =名称"class ="control-label"</label>< input asp-for =名称"class ="form-control"/>< span asp-validation-for =名称"class ="text-danger"</span></div>< div class ="form-group"><输入类型=按钮";value =保存";class ="btn btn-primary";onclick =" confirmEdit()"/></div></form></div></div>< div>< asp-action =索引">返回列表</a></div>@section脚本{< script>函数确认编辑(){swal({标题:"MIS",文字:案例创建您的案例编号为"+ $(#Id").val(),图标:警告",按钮:是的,angersMode:真,}).then((willUpdate)=> {如果(willUpdate){$ .ajax({网址:"/tests/edit/" + $(#Id").val(),类型:"POST",数据: {ID:$(#Id").val(),名称:$(#Name").val()},dataType:"html",成功:功能(){swal(完成!",已成功编辑!",成功").then((success)=> {window.location.href ="/tests/index";});},错误:函数(xhr,ajaxOptions,thrownError){swal(错误更新!",请重试",错误");}});}});}</script>} 

控制器:

 公共类TestsController:控制器{私有只读Mvc3_1Context _context;公共TestsController(Mvc3_1Context上下文){_context =上下文;}//GET:测试公共异步Task< IActionResult>指数(){返回View(await _context.Test.ToListAsync());}//GET:Tests/Edit/5公共异步Task< IActionResult>编辑(int?id){如果(id == null){返回NotFound();}var test =等待_context.Test.FindAsync(id);如果(测试==空){返回NotFound();}返回View(test);}[HttpPost]公共异步Task< IActionResult>编辑(int id,[FromForm]测试测试){如果(id!= test.Id){返回NotFound();}如果(ModelState.IsValid){_context.Update(test);等待_context.SaveChangesAsync();返回RedirectToAction(nameof(Index));}返回View(test);}} 

_Layout.cshtml:

与选项一相同.

结果:

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,
    })

解决方案

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:


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:

这篇关于在ASP.NET Core C#之后使用JavaScript代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆