【发布时间】:2011-08-15 03:07:10
【问题描述】:
对于 asp mvc3 客户端验证,是否可以将默认的、开箱即用的不显眼样式与 jquery 验证插件混合使用?
这是视图中的表单:
@using (Html.BeginForm("", "", FormMethod.Post, new { id = "newRatingForm" }))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Rating</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Rate)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Rate)
@Html.ValidationMessageFor(model => model.Rate)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
默认情况下,使用模型属性上的常用验证属性,Unobtusive 效果很好。目标是用 [fyneworks][1] jquery 星级插件替换表单中的“model.Rate”位,并仅对表单的该部分使用 jquery 验证插件:
<span>Your Rating:</span>
<div id="ratingStars">
<input class="star {split:2}" type="radio" name="Rating" value="0.5"/>
<input class="star {split:2}" type="radio" name="Rating" value="1.0"/>
<input class="star {split:2}" type="radio" name="Rating" value="1.5"/>
<input class="star {split:2}" type="radio" name="Rating" value="2.0"/>
<input class="star {split:2}" type="radio" name="Rating" value="2.5"/>
<input class="star {split:2}" type="radio" name="Rating" value="3.0"/>
<input class="star {split:2}" type="radio" name="Rating" value="3.5"/>
<input class="star {split:2}" type="radio" name="Rating" value="4.0"/>
<input class="star {split:2}" type="radio" name="Rating" value="4.5"/>
<input class="star {split:2}" type="radio" name="Rating" value="5.0"/>
</div>
我劫持了表单的提交操作并将表单值转换为 Json 以执行 ajax 请求:
$("#newRatingForm").submit(function (event) {
event.preventDefault();
if ($(this).valid()) {
newRatingSubmit();
}
});
function newRatingSubmit() {
//jquery ajax request using form values converted to Json
}
单选按钮似乎破坏了表单并且劫持代码不再起作用,即当我单击提交时,没有向服务器发出请求(在萤火虫控制台上观看)并且表单消失了。同样,只需简单的 mvc3 表单就可以正常工作。
我尝试为评分单选按钮添加 jquery 验证规则,但似乎没有任何区别:
$("#newRatingForm").validate({
meta: "validate",
errorLabelContainer: "#ErrorDiv",
wrapper: "div",
rules:
{
Rating: {
required: true
}
},
messages:
{
Rating: {
required: 'A Rating required.'
}
},
onfocusout: false,
onkeyup: false,
//handle validation ok, POST submit
submitHandler: function (label) {
newRatingSubmit();
}
});
作为替代方案,我可以使用 jquery 验证插件使用星级插件验证标准 html 表单,并使用上面的代码提交,但这似乎不是很“asp.net mvc”。例如,我需要两组验证消息 - 一组用于使用验证属性的服务器,另一组用于客户端视图。
【问题讨论】:
标签: jquery asp.net validation asp.net-mvc-3 plugins