c# - 如何在引导模式中触发 ASP.Net 核心模型验证和远程属性
问题描述
我想知道如何在提交之前在引导模式弹出中触发模型验证?我想从我的模式弹出窗口中触发所需的远程属性验证
这是我的模型代码:
public class Employee
{
public int Id { get; set; }
[Required]
[Remote("CheckFirstName", "Employees", ErrorMessage = "FirstName already exists.")]
public string FirstName { get; set; }
//code here
}
我的控制器代码:
public IActionResult Create()
{
Employee emp = new Employee();
return PartialView("_EmployeePartial", emp);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,FirstName,LastName,MI")] Employee employee)
{
//code here
return View(employee);
}
[AcceptVerbs("Post", "Get")]
public IActionResult CheckFirstName(string fname){
//code here
}
我的员工部分代码:
@model CrudApp.Models.Employee
<!-- Modal -->
<div class="modal fade" id="addEmployee" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<form asp-action="Create">
//code here
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-save="modal">Save changes</button>
</div>
</div>
</div>
</div>
调用模态的代码:
<button type="button" class="btn btn-primary" data-toggle="ajax-modal" data-target="#addEmployee"
data-url="@Url.Action("Create")">Create</button>
JS代码:
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
});
});
PlaceHolderElement.on('click', '[data-save="modal"]', function (event) {
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = form.serialize();
$.post(actionUrl, sendData).done(function (data) {
PlaceHolderElement.find('.modal').modal('hide');
});
});
解决方案
您正在触发控制器中不存在的CheckFirstName操作。
public IActionResult CheckFirstName(string FirstName)
{
// code to validate the FirstName
return Json(result); //return result in json example your validation message.
}
这将在您在 FirstName 文本框中输入输入时触发。
推荐阅读
- php - PHP INCLUDE - 注入可能?
- c# - 如何正确连接 Blazor 中动态创建的按钮?
- javascript - 无法使用 html + javascript 将 .xml 文件加载到 .php 文件中
- r - rasterFromXYZ() rasterFromXYZ() 中的错误:x 像元大小不规则
- c# - Dapper 在 DML 操作上返回模型(属性类)
- javascript - Javascript:在脚本运行之前不要完成加载页面
- mysql - 如何编写 SQL 查询以使用 3 个表查找百分比?
- python - 在 Python 中修改和访问类变量
- ios - 带有默认地图视图引脚的 Swift Mapview 自定义调出视图
- mysql - 如何在数据库初始化完成后停止填充卷的 MySQL docker 容器?