A
A
Artem D2018-02-02 21:50:38
ASP.NET
Artem D, 2018-02-02 21:50:38

What is the best way to handle such model binding?

I'm learning MVC, I have a small question
Let's say there is a model that has a Required field...
public class AddressModel {
[Required]
[AddressRemoteDropDownList(1, "id", null)]
[Display(Name = "Region", Order = 1) ]
public string RegionId { get; set; }
[AddressHidden(1, "code")]
[Display(Order = 2)]
public string RegionCode { get; set; }
}
There is a form model with a link to the address class (on the client, the block with the address is a pop-up window) -
public class FormModel {
...
public AddressModel Address
...
}
the block with the address is optional, the user may not open a pop-up window and fill in nothing ...
It turns out when sending the form to the server, the input value of the properties AddressModel = "" and the controller gets an object with all properties of the class AddressModel = null
And the ModelState swears, that RegionId is not filled...
How to be in such situation it is better, on good the Address property of the form should be null that server validation did not swear?
Or you need a custom ModelBinder, or even easier to solve (without removing the Required attribute from RegionId )
Sorry for the stupid question, thanks ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MrDywar Pichugin, 2018-02-02
@Dywar

We had a similar case, googled the Required method with a condition, done through a custom attribute. In it, according to any other properties of the model, it is determined whether the field should be required or not.
If in your case there is always a condition that the model has null in the required property and this cannot be distinguished from another requirement where it should not be null, then even AI will find it difficult to solve such a situation, it’s a joke, such a task cannot be solved. Otherwise, Required with a condition will do.
1) Google - Conditional Required Attribute
2) Use FluentValidation https://github.com/JeremySkinner/FluentValidation (this is a very powerful tool). Allows you to cut your validation conveniently and with perversions / any number of conditions.

A
Alexander, 2018-02-02
@alexr64

Validate the model yourself .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question