Nikolay Kostov
Nikolay Kostov

Reputation: 16963

KendoUI Grid Default Value with Data Annotation

I am using Kendo UI Grid with ASP.NET MVC Helpers and auto generated columns.

I have [DefaultValue(60 * 60)] annotation in my view model but Kendo helpers doesn't seem to respect that.

Can I have default value specified (probably with data annotations) without having to manually describe the columns?

Upvotes: 4

Views: 5583

Answers (2)

Monah
Monah

Reputation: 6784

if you defined the columns in the grid manually, you need to set the default value like this despite you defined the default value in the annotation or not

 @(Html.Kendo()
      .Grid()
      .DataSource( d=> d.Ajax()
                        .Model(m=>{
                            m.Field(f=>f.YourField).DefaultValue(YourValue);
                 }))
)

so for the auto-generated columns you can try the following

@(Html.Kendo()
      .Grid()
      .Events( e => e.Edit("onEdit"))
)

<script type="text/javascript">
      function onEdit(e) {   
           //check if record is new
           if (e.model.isNew()) {
                // set the value of the model property like this                    
                e.model.set("PropertyName", Value);
                // for setting all fields, you can loop on 
                // the grid columns names and set the field
           }
    }
</script>

hope this will help you

Upvotes: 7

Matt Millican
Matt Millican

Reputation: 4054

For default values, I like using the constructor which I believe Kendo should new-up an instance of your model, so this would work.

View mode

public class ViewModel
{

    public string Name { get; set; }

    public ViewModel()
    {
        Name = "First name";
    }

}

EDIT

After doing some searching in their docs, it appears that the data annotations or constructor default value are not supported and you must define the default values in the grid definition. See http://docs.telerik.com/kendo-ui/aspnet-mvc/helpers/grid/faq#how-do-i-specify-default-property-values-when-a-new-item-is-created for more.

Upvotes: 2

Related Questions