asp.net mvc 4 - MVC RequiredIf Attribute - IsValid value parameter always null -
i implementing requiredif validation attribute , value being passed isvalid method null.
requiredifattribute class
public class requiredifattribute : validationattribute { private requiredattribute innerattribute = new requiredattribute(); public string dependentproperty { get; set; } public object targetvalue { get; set; } public requiredifattribute(string dependentproperty, object targetvalue) { this.dependentproperty = dependentproperty; this.targetvalue = targetvalue; } public override bool isvalid(object value) { return innerattribute.isvalid(value); } }
viewmodel
[required] [display(name = "are student?")] public bool? isstudent { get; set; } [requiredif("isstudent", true, errormessage = "you must upload photo of student id if wish register student.")] [display(name = "student id")] [fileextensions("jpg|jpeg|png|pdf", errormessage = "file not in correct format.")] [maxfilesize(2 * 1024 * 1024, errormessage = "you may not upload files larger 2 mb.")] public httppostedfilebase studentid { get; set; }
editortemplate
@model bool? @using system.web.mvc; @{ var options = new list<selectlistitem> { new selectlistitem { text = "yes", value = "true", selected = model.hasvalue && model.value }, new selectlistitem { text = "no", value = "false", selected = model.hasvalue && model.value } }; string defaultoption = null; if (viewdata.modelmetadata.isnullablevaluetype) { defaultoption = "(select)"; } } @html.dropdownlistfor(m => m, options, defaultoption)
every time form submitted, requiredif error message thrown , have feeling has null value described initially. doing wrong? thanks!
note: html appears rendering properly, don't think that's problem.
<select data-val="true" data-val-required="the student? field required." id="isstudent" name="isstudent"><option value="">(select)</option> <option value="true">yes</option> <option value="false">no</option> </select>
because code -
public class requiredifattribute : validationattribute { private requiredattribute innerattribute = new requiredattribute(); public string dependentproperty { get; set; } public object targetvalue { get; set; } public requiredifattribute(string dependentproperty, object targetvalue) { this.dependentproperty = dependentproperty; this.targetvalue = targetvalue; } public override bool isvalid(object value) { return innerattribute.isvalid(value); } }
you using requriedatrribute
. simulate behaves life requiredif
have implement logic check whether target property value true or false. not doing , returning innerattribute. mere required
not requiredif
-
public override bool isvalid(object value) { return innerattribute.isvalid(value); }
modify function checking -
public override bool isvalid(object value) { //if referred property true return innerattribute.isvalid(value); //else return true }
Comments
Post a Comment