English 中文(简体)
视力模型中物体的验证不增加科学、技术和科学部的验证类别
原标题:Validation of objects in ViewModel not adding CSS validation classes

我有以下看法模式:

public class Search {
    public int Id { get; set; }

    [Required(ErrorMessage = "Please choose a name.")]
    public string Name { get; set; }

    [ValidGroup(ErrorMessage = "Please create a new group or choose an existing one.")]
    public Group Group { get; set; }
}

public class Group {
    public int Id { get; set; }
    public string Name { get; set; }
}

我对习俗鉴定作了如下定义:

public class ValidGroupAttribute : ValidationAttribute {
    public override bool IsValid(object value) {
        if (value == null)
            return false;

        Group group = (Group)value;

        return !(string.IsNullOrEmpty(group.Name) && group.Id == 0);
    }
}

我有以下看法(一些简短的看法):

    @Html.ValidationSummary()

    <p>
        <!-- These are custom HTML helper extensions. -->
        @Html.RadioButtonForBool(m => m.NewGroup, true, "New", new { @class = "formRadioSearch", id = "NewGroup" })
        @Html.RadioButtonForBool(m => m.NewGroup, false, "Existing", new { @class = "formRadioSearch", id = "ExistingGroup" })
    </p>
    <p>
        <label>Group</label>
        @if (Model.Group != null && Model.Group.Id == 0) {
            @Html.TextBoxFor(m => m.Group.Name)
        }
        else {
            @Html.DropDownListFor(m => m.Group.Id, Model.Groups)
        }
    </p>

问题Im是验证类别input-validation-error,没有适用于专家组的投入。 我认为,这是因为该框架试图找到一个有<代码>id=“Group”的外地,而正在生成的标识有id=”Group_Idid=Group_Name。 是否有办法应用这一类别?

http://f.cl.ly/items/0Y3R0W3Z193s3d1h3518/Capture.PNG

Update

I ve Trial implementing IValidatable 目标在专家组看来是模型,而不是使用验证属性,但我仍然不能让中心级适用:

public class Group : IValidatableObject
{
    public int Id { get; set; }
    public string Name { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
        if (string.IsNullOrEmpty(Name) && Id == 0) {
            yield return new ValidationResult("Please create a new group or select an existing one.", new[] { "Group.Name" });
        }
    }
}

Update 2

自我验证不工作。 我认为,这是因为在MVC框架中使用的“ValidationResult中的第二个参数”。

http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2”rel=“nofollow noreferer” http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2

在某些情况下,你可能会被诱惑,使用第二座建筑商超载ValidationResult,其成员名数不一。 例如,你可以决定,你想要在这两个领域展示错误信息,这样,你就将守则改为:

return new ValidationResult( FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName, OtherProperty });

如果你执行你的法典,你将绝对没有任何区别。 这是因为,虽然这种超负荷存在,而且大概在其他地方使用。 NET框架,MVC框架完全无视ValidationResult。 成员

最佳回答

我提出解决办法,但显然是一项工作。

我删除了验证属性,并创建了一种习惯模型约束器,而该模型人工添加了一个错误,在<代码>ModelState上添加了一个错误。

public class SearchBinder : DefaultModelBinder {
    protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext,
       PropertyDescriptor propertyDescriptor) {
        if (propertyDescriptor.Name == "Group" &&
            bindingContext.ValueProvider.GetValue("Group.Name") != null &&
            bindingContext.ValueProvider.GetValue("Group.Name").AttemptedValue == "") {
            ModelState modelState = new ModelState { Value = bindingContext.ValueProvider.GetValue("Group.Name") };
            modelState.Errors.Add("Please create a new group or choose an existing one.");
            bindingContext.ModelState.Add("Group.Name", modelState);
        }
        base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
    }
}

// Register custom model binders in Application_Start()
ModelBinders.Binders.Add(typeof(SearchViewModel), new SearchBinder());

有了<代码>ModelState[“Group.Name”>,现在有了一个错误的条目,在标识中正在提供CSS。

不过,如果在多国师协会中找到一种办法,则我更愿意这样做。

Solved!

Found a proper way to do this. I was specifying the wrong property name in the self validating class, so the key that was being added to the ModelState dictionary was Group.Group.Name. All I had to do was change the returned ValidationResult.

yield return new ValidationResult("Please create a new group or select an existing one.", new[] { "Name" });
问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签