简体   繁体   中英

ASP.NET MVC Using view models in different views

I have 2 customer views one for create and one for edit. I am using the same customer view model for both. I want to make the 'customer no field' required on the add, but not the edit.

If I put the requiredfield attribute on the view model property then both views flag 'Customer No' as required (as you would expect).

Is there a built in solution to get around this problem or Am I going to have to create 2 seperate view models, one with the attribute and one without.

Thanks

This is similar to this question .

I would strongly advise you to tailor 2 View Models for edit and create actions. It is a lot cleaner. The last answer in the link I gave you makes a workaround and disables the errors on the ModelState.

How is Customer No. required on create but not edit?

If you create it, it requires the number, and when you edit it, the number is still there.

Do you mean they can remove the customer number on edit? Or do you mean you want Customer no. to be non-editable on edit?

If it's the latter, then you can keep customer no as required, you just display the customer no in your edit view (not in a textbox) and use a hidden input to contain the number so it gets posted.

Just a concept type of suggestion. Remove the required validation attribute from your model. In your controller, make the parameter optional and depending on which Action (Edit or Create), you'll manually add in some type of validation.

The jQuery validation can be used to validate from the client based on the input if you go towards the manual route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM