开发者

ASP.NET MVC3 Client side validation

I am building a search form for my web application using MVC3. My form is basically divided in two sections. 1st Section has 3 search criteria. First Name, Last Name and Zip code and beneath that section there is a "Search" button which I can click and it should do a client side validation and give me an error message if any of 开发者_开发百科the fields are blank.

2nd section on the same page has just one textbox - to search by "Quote Number". So that section has one textbox to enter quote number and beneath there is another button called "Search". When I click on this search button it should only validate that the Quote Number field is not empty.

I have a viewmodel which has all 4 properties (FName,LName,Zip,Quote Number) and I am binding that on the page. Both the button will post back the page (I know that there is a way to identify which button was clicked on postback). The problem I am facing is on postback everything is posting back and if I use datannotations to do RequiredField check, it does validation on all the 4 fields but I should check for which button is clicked and based on that only fire validation on either 3 fields or only on 1 fields. How do I achieve this functionality? I hope I clearly explained the issue.

Thanks


Since this is MVC, don't think of these as postbacks, think of them as submits. As they are searching by different criteria, they should really be two different forms submitting to two different actions. As they are separate actions, each can have it's own view with it's own ViewModel and validation. Then to combine them into one physical page to present to the user just use partial rendering to put them both into the same view.

Basically the view you present to the user would have something like:

@{
    Html.RenderAction("SearchByName");
}
<!-- maybe some markup to visually separate them -->
@{
    Html.RenderAction("SearchByQuote");
}

Also gives you the added benefit of having each action be responsible for a single task and you don't have to put in code to figure out which button was clicked, etc.


And just in case you think to yourself "Hey, since both are search, just with different number of parameters, can't I overload the Search action?" No.


Kevin,

Change your page so that you have two different forms, one for each search type. When you click submit in one form, only that form's child fields will be validated.

Then, as R0MANARMY suggested, have two separate actions, one for each search form.

counsellorben

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜