除了在cshtml中提交之外,如何对其他按钮使用验证?
Posted
技术标签:
【中文标题】除了在cshtml中提交之外,如何对其他按钮使用验证?【英文标题】:How to use validation for other button except than submit in cshtml? 【发布时间】:2021-01-01 21:48:41 【问题描述】:我已经为 cshtml 编写了一个 html 代码,其中包含两个按钮保存和更新:
<div class="modal-body">
@using (Html.BeginForm("Create", "CustomActivity", FormMethod.Post, new role = "form", @id = "customActivityForm", @class = "activityForm" ))
<div>
<div class="container" id="activity">
@Html.LabelFor(m => m.AdminCustomActivity.Activity, new @class = "" )
@Html.TextBoxFor(m => m.AdminCustomActivity.Activity, new @class = "w100p mb0" )
@Html.ValidationMessageFor(m => m.AdminCustomActivity.Activity, "", new @class = "text-danger" )
</div>
<div class="container">
<div class="column one-fourth">
<div>
@Html.LabelFor(m => m.AdminCustomActivity.Rate, new @class = "wcrate" )
@Html.TextBoxFor(m => m.AdminCustomActivity.Rate, new @class = "w100p mb0" )
@Html.ValidationMessageFor(m => m.AdminCustomActivity.Rate, "", new @class = "text-danger" )
</div>
</div>
</div>
<div class="modal-footer">
@Html.HiddenFor(m => m.AdminCustomActivity.WorkOrderId, new @id = "hfWorkOrderId" )
@Html.HiddenFor(m => m.AdminCustomActivity.Id, new @id = "customActivityId" )
<button type="submit" class="btn btn-primary">Create</button>
<button class="btn btn-primary" id="updateActivity">Update</button>
</div>
</div>
</div>
现在页脚中有两个按钮添加和更新,验证非常适合添加按钮,但验证不适用于更新按钮,因为更新按钮的函数调用来自 jquery
$("#updateActivity").click(function ()
event.preventDefault();
$.ajax(
type: "POST",
url: "/CustomActivity/Update",
data:
WorkOrderId: @Model.Id,
,
success: function ()
location.reload();
window.scrollTo(0, 0);
,
error: function ()
//alert(erro.data)
);
)
如何允许检查更新按钮中的验证与添加按钮相同。我尝试使用 type='submit'
但这不起作用
【问题讨论】:
@CarstenLøvboAndersen 不,那是剃刀视图中模型的价值,它的作用是``` @Model.Id ``` 【参考方案1】:您必须调用实现jQuery validatation 的函数才能在单击更新按钮时显示验证消息:
function validateUpdate()
$("#customActivityForm").validate(
rules:
AdminCustomActivity_Activity: "required",
AdminCustomActivity_Rate: "required"
);
$("#updateActivity").click(function ()
validateUpdate();
$.ajax(
type: "POST",
url: "/CustomActivity/Update",
data:
WorkOrderId: @Model.Id,
,
success: function ()
location.reload();
window.scrollTo(0, 0);
,
error: function ()
//alert(erro.data)
);
)
【讨论】:
是它验证必填字段并显示错误消息,但在显示错误消息后它仍然通过ajax调用API。只有在没有任何验证错误的情况下,有没有办法通过ajax调用API? 我用过 if (validateUpdate()) ///ajax call 但没用 我觉得你可以用if($("#customActivityForm").valid())
以上是关于除了在cshtml中提交之外,如何对其他按钮使用验证?的主要内容,如果未能解决你的问题,请参考以下文章