Asp.net core Post关联的几种方法
假定我们的页面是Index.cshtml和Index.cshtml.cs
1. 属性绑定,添加模型绑定[BindProperty]
Index.cshtml
<form class="form-inline" role="form" method="post">
<div class="form-group">
<label for="name">名称:</label>
<input type="text" asp-for="@Model.Test1" placeholder="请输入名称">
<input type="submit" value="提交" class="btn btn-primary btn-sm" />
<span asp-validation-for="@Model.Test1" class="text-danger"></span>
</div>
</form>
@*合法性判断*@
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Index.cshtml.cs
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public string Message;
[BindProperty] // 需要绑定post才有作用
[Required(ErrorMessage = "First Number is required.")] // 验证与错误信息
[StringLength(10)]
public string Test1 { get; set; }
public void OnPost( )
{
if (ModelState.IsValid)
{
Message = Test1;
}
}
}
可以设置多个绑定属性,无须在OnPost中添加参数
2. 使用asp-page-handler标记
下面例子中携带了两个参数int id和string strinfo
Index.cshtml
<form asp-page-handler="view" method="post">
<input name="id" value="3" />
<input name="strinfo" value="abc" />
<button class="btn btn-default">查看</button>
</form>
@*合法性判断*@
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Index.cshtml.cs
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public string Message;
public void OnPostView(int id, string strinfo)
{
Message = $"View handler fired for {id}, {strinfo}";
}
}
其中asp-page-handler=“view” 对应OnPostView,格式为OnPost+handler,handle不区分大小写