views:

706

answers:

2

Hi I have the following cod throughout my app but with just two fields it's not working.

[Required]        
public string DevelopmentPM { get; set; }

The following test runs and passes:

    [TestMethod]
    public void SiteConstruction_MODEL_DevelopmentPM_Is_Required()
    {
        //arrange
        var propertyInfo = typeof(SiteConstructionMetadata).GetProperty    
                           ("DevelopmentPM");

        //act
        var attribute = propertyInfo.GetCustomAttributes(typeof(RequiredAttribute), 
                        true).Cast<RequiredAttribute>().FirstOrDefault();

        //assert
        Assert.IsNotNull(attribute);
    }

My controlller looks like:

        TryUpdateModel(siteConstruction);

        if (!ModelState.IsValid)
           return View(siteConstruction);

I have other required fields in model and they are OK. This field is null (I checked) but doesn't make the model invalid - so no validation and an error on save.

My View

    <li>
        <label for="DevelopmentPM">
            <strong>Development PM:</strong></label>
        <%= Html.TextBox("DevelopmentPM") %>
        <%= Html.ValidationMessage("DevelopmentPM", "*") %>
    </li>

I've looked at my .dbml (Linq to SQl), spelling looks ok.

I'm I missing something simple - please, going mad.

Thanks

Davy

A: 

Make sure you make the DataAnnotationsModelBinder the default model binder too. Add the following in your Global.asax.cs:

ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();

and make sure that you have referenced the System.ComponentModel.DataAnnotations.dll assembly in your project. See this tutorial for more details.

Tomas Lycken
Thanks - no I have that - as I said - This exact code is working elsewhere.I've debugged and even if I explicitly set thge field to null in the controller - the model is still valid.
Davy
A: 

[MetadataType(typeof(SiteConstructionMetadata))] above my partial class, I took it for granted I had it there.

Next time, instead of posting snippets, I think I'll post it all - smeone wous have spotted that pretty quickly.

Davy

Davy