gpt4 book ai didi

asp.net-mvc-3 - MVC3 客户端验证不适用于 Ajax.BeginForm 表单

转载 作者:行者123 更新时间:2023-12-04 12:07:07 27 4
gpt4 key购买 nike

我在局部 View 中有以下形式

@model PartDetail
@using (Ajax.BeginForm("Create", "Part", null, new AjaxOptions { UpdateTargetId = "update_panel"}))
{
<h3>New @Model.PartType</h3>
<p> Serial Number:
<strong>
@Html.EditorFor(model => model.SerialNumber)
@Html.ValidationMessageFor(model => model.SerialNumber)
</strong>
</p>
<p> Name:
<strong>
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</strong>
</p>
...... more relatively boiler plate code here......
<p>
<input type="submit" class="btn primary" value="Save Part"/>
</p>
}

用一个模型
public class PartDetail
{
public string DateCreated { get; set; }
[StringLength(255, MinimumLength = 3)]
public string Description { get; set; }
public Guid ID { get; set; }
public string IsActive { get; set; }
public string Manufacturer { get; set; }
public IEnumerable<SelectListItem> Manufacturers { get; set; }
[StringLength(100, MinimumLength = 3)]
public string Name { get; set; }
public string PartType { get; set; }
[Required]
[StringLength(100, MinimumLength = 3)]
public string SerialNumber { get; set; }
}

我引用(在我的部分 View 的父 View 中)
<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"> </script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"> </script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"> </script>

没有任何东西得到验证。如果我没有在序列号文本框中输入任何内容并按提交,它会毫无问题地将其保存到数据库中。

最佳答案

尝试添加 OnBegin 回调到 AjaxOptions,这应该可以工作。

function validateForm() { 
return $('form').validate().form();
}

@using (Ajax.BeginForm("Create", "Part", null, new AjaxOptions { UpdateTargetId = "update_panel", OnBegin = "validateForm" }))
...

如果这对您不起作用,请发送 替代解决方案 可能是使用jQuery提交表单。这将是我首选的解决方案。
<div id="result"></div> 

@using (Html.BeginForm())
{
<h3>New @Model.PartType</h3>
<p>Serial Number:
<strong>
@Html.EditorFor(model => model.SerialNumber)
@Html.ValidationMessageFor(model => model.SerialNumber)
</strong>
</p>
<p> Name:
<strong>
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</strong>
</p>
...... more relatively boiler plate code here......
<p>
<input type="submit" class="btn primary" value="Save Part"/>
</p>

}

jQuery/JS 提交表单的函数
    $(function () { 
$('form').submit(function () {

$.validator.unobtrusive.parse($('form')); //added

if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});

关于asp.net-mvc-3 - MVC3 客户端验证不适用于 Ajax.BeginForm 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8894764/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com