刚刚开始使用.net core 2.0 Razor进行web开发,上来就遇到一点小问题,在前端页面如何调用ajax,网上的文章很多,但大多是传统的MVC架构,即通过ajax调用controller,虽可以使用但总不理想。Razor2.0使用handler处理页面请求的结构,并可以通过asp-page-hanlder来调用不同的处理方法,经过2天测试,终于达到预期效果,为了怕以后忘记记录下全部过程。整个项目只有一个测试页面,两个按钮分别对应get和post方法:
环境:WIN10pro+VS2107pro
环境:WIN10pro+VS2107pro
1. 新建Asp.net Core Web应用程序Core20RazorAjax
2. 在Pages文件夹新建一个Razor页面:RazorAjax
3. 系统自动生成2个文件,前端页面以cshtml为扩展名,后端页面以.cshtml.cs为扩展名,后端页面里自动生成一个默认的OnGet方法,现在到页面里添加一个按钮,调用后端的方法来显示一个简单信息
<h2>RazorAjax</h2>
<div id="AjaxStr" style="font-size:24px;"></div>
<input type="button" id="btnGet" value="Get数据">
@section Scripts{
<script type="text/javascript" language="JavaScript">
$('#btnGet').on('click', function () {
$.ajax({
type: "GET",
url: "/RazorAjax?handler=AjaxStr",
contentType: "application/json",
dataType: "json",
success: function (response) {
var strAjax = $("#AjaxStr");
strAjax.empty();
$('<A>').append(response).appendTo(strAjax);
},
failure: function (response) {
alert(response);
}
})
})
</script>
}
在后台RazorAjax.cshtml.cs页面里添加方法
public JsonResult OnGetAjaxStr()
{
return new JsonResult("测试Get方法获取后台数据!");
}
4. 运行,并访问 http://localhost:xxxxx/RazorAjax 点击按钮就可以调出后台字符串
5. 下面开始测试post方法,由于post方法会遇到跨域保护cross-site-request-forgery(CSRF/XSRF),所以要在配置里添加设置
首先在Startup.cs里添加配置
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
}
修改页面文件,增加post测试内容
<h2>使用post上传参数并获取返回结果</h2>
@Html.AntiForgeryToken()
字符参数1: <input type="text" id="paramStr" value="字符串参数" /><br />
整形参数2: <input type="text" id="paramInt" value=100 /><br />
日期参数3: <input type="text" id="paramDate" value="1970-01-01" /><br /><br />
<input type="button" id="btnPost" value="Post调用">
<h3 style="color:brown;">返回结果</h3>
<div id="PostResult">
</div>
......
$('#btnPost').on('click', function () {
var param1 = $('#paramStr').val();
var param2 = $('#paramInt').val();
var param3 = $('#paramDate').val();
$.ajax({
type: "POST",
url: "/RazorAjax?handler=AjaxPost",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify({
Param1: param1,
Param2: param2,
Param3: param3
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var pr = $("#PostResult");
pr.empty();
$.each(response, function (i, item) {
var $tr = $('<li>').append(item).appendTo(pr);
});
},
failure: function (response) {
alert(response);
}
});
})
修改后台页面,添加post处理
public JsonResult OnPostAjaxPost()
{
string str1 = "";
string str2 = "";
string str3 = "";
{
MemoryStream stream = new MemoryStream();
Request.Body.CopyTo(stream);
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream))
{
string requestBody = reader.ReadToEnd();
if (requestBody.Length > 0)
{
var obj = JsonConvert.DeserializeObject<Params>(requestBody);
if (obj != null)
{
str1 = obj.param1 + "- 后台处理返回";
str2 = (obj.param2 + new Random().Next(1000,9999)).ToString();
str3 = obj.param3.ToLongDateString();
}
}
}
}
List<string> lstString = new List<string>
{
str1,
str2,
str3
};
return new JsonResult(lstString);
}
}
6. 测试运行
7. 附注:如果对url写法不舒服/xxx/?handler=xxx,可以在页面开始部分添加@page "{handler?}",则url可以写成/xxx/handler的方式
8. 全部代码
--Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Core20RazorAjax
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
app.UseStaticFiles();
app.UseMvc();
}
}
}
--RazorAjax.cshtml
@page "{handler?}"
@model Core20RazorAjax.Pages.RazorAjaxModel
@{
ViewData["Title"] = "RazorAjax";
}
<h2>使用get获取数据</h2>
<input type="button" id="btnGet" value="Get数据">
<div id="AjaxStr" style="font-size:24px;"></div>
<br />
<br />
<h2>使用post上传参数并获取返回结果</h2>
@Html.AntiForgeryToken()
字符参数1: <input type="text" id="paramStr" value="字符串参数" /><br />
整形参数2: <input type="text" id="paramInt" value=100 /><br />
日期参数3: <input type="text" id="paramDate" value="1970-01-01" /><br /><br />
<input type="button" id="btnPost" value="Post调用">
<h3 style="color:brown;">返回结果</h3>
<div id="PostResult">
</div>
@section Scripts{
<script type="text/javascript" language="JavaScript">
$('#btnGet').on('click', function () {
$.ajax({
type: "GET",
url: "/RazorAjax/AjaxStr",
contentType: "application/json",
dataType: "json",
success: function (response) {
var strAjax = $("#AjaxStr");
strAjax.empty();
$('<A>').append(response).appendTo(strAjax);
},
failure: function (response) {
alert(response);
}
})
});
$('#btnPost').on('click', function () {
var param1 = $('#paramStr').val();
var param2 = $('#paramInt').val();
var param3 = $('#paramDate').val();
$.ajax({
type: "POST",
url: "/RazorAjax/AjaxPost",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify({
Param1: param1,
Param2: param2,
Param3: param3
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var pr = $("#PostResult");
pr.empty();
$.each(response, function (i, item) {
var $tr = $('<li>').append(item).appendTo(pr);
});
},
failure: function (response) {
alert(response);
}
});
})
</script>
}
--RazorAjax.cshtml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Newtonsoft.Json;
namespace Core20RazorAjax.Pages
{
public class RazorAjaxModel : PageModel
{
public void OnGet()
{
}
public JsonResult OnGetAjaxStr()
{
return new JsonResult("测试Get方法获取后台数据!");
}
public JsonResult OnPostAjaxPost()
{
string str1 = "";
string str2 = "";
string str3 = "";
{
MemoryStream stream = new MemoryStream();
Request.Body.CopyTo(stream);
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream))
{
string requestBody = reader.ReadToEnd();
if (requestBody.Length > 0)
{
var obj = JsonConvert.DeserializeObject<Params>(requestBody);
if (obj != null)
{
str1 = obj.param1 + "- 后台处理返回";
str2 = (obj.param2 + new Random().Next(1000,9999)).ToString();
str3 = obj.param3.ToLongDateString();
}
}
}
}
List<string> lstString = new List<string>
{
str1,
str2,
str3
};
return new JsonResult(lstString);
}
}
public class Params
{
public string param1 { get; set; }
public int param2 { get; set; }
public DateTime param3 { get; set; }
}
}