1

I have a situation where I want to be in the model was required only one field of the two.

    public int AutoId { get; set; }
    public virtual Auto Auto { get; set; }

    [StringLength(17, MinimumLength = 17)]
    [NotMapped]
    public String VIN { get; set; }

If someone entered the vin, it is converted in the controller on the AutoID. How to force the controller to something like this work?

         public ActionResult Create(Ogloszenie ogloszenie) {
        information.AutoId = 1;         
        if (ModelState.IsValid)
        {
        ...
        }..
user1644160
  • 277
  • 2
  • 6
  • 12
  • sorry, hmm I have a form. In this form, the two fields. User has to fill one of them. Filling one will be required. One field shows the AutoID and the other on the VIN. When the user fills AutoID, everything is ok. When complete VIN, ModelState.IsValid is false: (Before checking ModelState AutoID field is completed. – user1644160 Oct 25 '12 at 13:11

2 Answers2

1

You can implement a custom validation attribute that will check presence of either of the required fields.

more on custom validatio attributes: How to create custom validation attribute for MVC

Community
  • 1
  • 1
dark_ruby
  • 7,646
  • 7
  • 32
  • 57
0

Try to use this approach:

controller:

public ActionResult Index()
{
    return View(new ExampleModel());
}

[HttpPost]
public ActionResult Index(ExampleModel model)
{
    if (model.AutoId == 0 && String.IsNullOrEmpty(model.VIN))
        ModelState.AddModelError("OneOfTwoFieldsShouldBeFilled", "One of two fields should be filled");
    if (model.AutoId != 0 && !String.IsNullOrEmpty(model.VIN))
        ModelState.AddModelError("OneOfTwoFieldsShouldBeFilled", "One of two fields should be filled");
    if (ModelState.IsValid)
    {
        return null;
    }
    return View();
}

view:

@using(Html.BeginForm(null,null,FormMethod.Post))
{
    @Html.ValidationMessage("OneOfTwoFieldsShouldBeFilled")

    @Html.TextBoxFor(model=>model.AutoId)

    @Html.TextBoxFor(model=>model.VIN)
    <input type="submit" value="go" />
}
Arun Manjhi
  • 175
  • 9
testCoder
  • 7,155
  • 13
  • 56
  • 75