public class FlaggedPublishedSongViewModel : ValidationAttribute, IClientValidatable
{
public int Id { get; set; }
public int PublishedSongId { get; set; }
public string Reason { get; set; }
public string AdditionalDetails { get; set; }
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule();
rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
rule.ValidationParameters.Add("AdditionalDetails", AdditionalDetails);
rule.ValidationType = "isempty";
yield return rule;
}
}
[HttpPost]
public ActionResult RequestDeletion(FlaggedPublishedSongViewModel song)
{
db.FlaggedPublishedSongs.Add(song);
db.SaveChanges();
TempData["UserMessage"] = "Thank you for the report";
return RedirectToAction("Index");
}
@model SoundVast.Areas.Music.Models.FlaggedPublishedSongViewModel
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.HiddenFor(x => Model.PublishedSongId)
@Html.RadioButtonFor(x => x.Reason, "Quality", new { @class = "radio-button-list" })
@Html.RadioButtonFor(x => x.Reason, "Duplicate", new { @class = "radio-button-list" })
@Html.RadioButtonFor(x => x.Reason, "Copyright", new { @class = "radio-button-list" })
@Html.RadioButtonFor(x => x.Reason, "Inappropriate", new { @class = "radio-button-list" })
@Html.RadioButtonFor(x => x.Reason, "Other", new { @class = "radio-button-list" })
@Html.TextAreaFor(x => Model.AdditionalDetails, new { @class = "additional-details", @placeholder = "Please be specific about any additional details" })
<br />
<button class="btn btn-default">Flag Song</button>
}
Jquery文件:
jQuery.validator.unobtrusive.adapters.addSingleVal("isempty", "AdditionalDetails");
jQuery.validator.addMethod("isempty",
function (val, element, other) {
var modelPrefix = element.name.substr(
0, element.name.lastIndexOf(".") + 1)
var otherVal = $("[name=" + modelPrefix + other + "]").val();
if (val && otherVal) {
if (val.toUpperCase() == "OTHER" && other.length <= 0) {
return false;
}
}
return true;
}
);
我正在尝试为"Other"
单选复选框和文本区域添加客户端验证。
从ValidationAttribute转发似乎导致错误:“值不能为空。\ r \ nParameter name:entitySet”,当我尝试对我的数据库执行任何操作时,例如db.PublishedSongs.ToList();
如果我不从这个基类继承,我的应用程序会运行,但验证器.addMethod永远不会运行。我还包括Jquery验证ajax和验证unob。
jquery addSingleVal
和addMethod
都被声明为没有错误,所以我认为这是我的viewmodel错误。