开发者

How to do conditional required field validations in ASP.net MVC2

I have 2 , one is update user details another is change password panel. Bo开发者_开发百科th has separate "update" button. I don't want user details part to be validated when I click on update button of change password and the vice versa applies the same. Presently I am using the following code in View.

    [Required]
    [DataType(DataType.Password)]
    [DisplayNameLocalized(typeof(CapnorResource), "RepeatNewPassword")]
    public string RepeatNewPassword { get; set; } 

in UI following is the code.

        <div class="passwordtd">
            <%: Html.LabelFor(view => view.RepeatNewPassword)%>
            <%: Html.PasswordFor(view => view.RepeatNewPassword)%>
            <%: Html.ValidationMessageFor(view => view.RepeatNewPassword)%>
        </div>


I'm not quite sure from the wording of the question, but with two different buttons, it sounds like two different forms with two different ViewModels. The ViewModels could make up one large ViewModel, or you could use RenderPartial to separate them completely.


I had same scenario with little twist. I had a single Account page and change password is a rendered as partial inside the main page, the change password has its own update button and the partial is rendered inside a div id="secure" tag which gets hidden in $(document).ready(). There is a link on main account details page which unhides the div.

I acheived partial validation as follows.
1)Created a temporary div out side the form tag.
2)On $(document).ready() I append the change password partial to the temporary div so when the main Account Details validation are fired the change Password's validation are not fired.
3) when the link to unhide the change password partial is clicked I again append the change password partial to form and then on Update button of change password partial I manually call validation mehods

var validator = $("form").validate(); var oldpass = document.getElementById("OldPasswordfeild"); var newpass = document.getElementById("NewPasswordfeild"); var conpass = document.getElementById("ConfirmPasswordfeild");

        if (!validator.element(oldpass) || !validator.element(newpass) || !validator.element(conpass)) 
        {
            isvalid = false;

        }

so only change password partials validation are fired and if they are valid I make a ajax post to my controller and if it is successful hide the div and again append it to temporary div out side the form.

Above thing works like a charm.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜