asp.net MVC 使用Ajax.BeginForm 无刷新提交from表单

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012949563/article/details/79172541

新建MVC项目 MVC5测试 




在 Models文件夹下新建类 TestViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MVC5测试.Models
{
    public class TestViewModel
    {
        public string name { get; set; }
        public string pw { get; set; }
    }
}


在Controllers 下新建控制器 Test,


增加Action Submit 提交方式是post 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVC5测试.Controllers
{
    public class TestController : Controller
    {
        // GET: Test
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Submit()
        {
            return PartialView();
        }
    }
}

为Test控制器的Index添加视图,模型是之前新建的TestViewModel


@model MVC5测试.Models.TestViewModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>  
</head>
<body>
    <div>
        @using (Ajax.BeginForm("Submit", "Test", new AjaxOptions
        {
            HttpMethod = "Post",
            UpdateTargetId = "update",
            InsertionMode = InsertionMode.Replace
        }))
        {
            @Html.TextBoxFor(o => o.name)
            @Html.TextBoxFor(o => o.pw, new { type = "password" })

            <button type="submit" style="width:80px; height:30px;">提交</button>
        }
        <br />
        <div id="update"></div>
    </div>
</body>
</html>

为  Submit添加视图 


<div>
    测试
</div>

测试Text/Index,发现不会实时更新,而是重新打开页面,是因为没有增加JS文件

打开BundleConfig.cs 如果没有jquery.unobtrusive-ajax.js

从Nuget下载 


在视图里增加 js引用

    @Scripts.Render("~/bundles/jquery", "~/bundles/jqueryval")
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

保存测试


代码下载地址 : 点击打开链接






猜你喜欢

转载自blog.csdn.net/u012949563/article/details/79172541