2

When we click on the Add New or Edit button using Kendo UI Grid, how do we set the default value for any model field?

For example I have two view models City and State. City view model contains the StateID as the foreign key to the City model.

Let's assume that I have a view page where I select from a State dropdownlist to get a Kendo Grid populated with the list of cities for that state. Now I want to create a new city within that state so I need to set the StateID value to the selected value from the dropdownlist.

How do I achieve this functionality?

4

2 回答 2

5

Well I spent quite some time to figure out the above issue till I stumbled upon this link. And the solution was pretty easy.

All I need to do is add "Edit" event and specify the javascript function which will be called on edit for the Kendo UI grid. Then we can set the default value on the javascript function.

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

<script type="text/javascript">
function onEdit(e) {

    var stateID = $("#hfStateID).val(); // I have set the dropdownlist selected value to  //the hidden field

    //check if record is new
    if (e.model.isNew()) {
        //set the default value for StateID
        e.model.set("StateID", stateID );
    }
}
</script>

Thought it might help someone.

Thanks.

于 2013-11-12T23:02:05.560 回答
1

Agree with the ajexpess.

I also had to remove the Required DataAnotation.

For example Remove: [Required(ErrorMessage = "Value should not be empty")] from the property you are trying to set.

于 2014-02-21T18:54:48.077 回答