Telerik Forums
UI for ASP.NET MVC Forum
2 answers
382 views
Hi

I'm having an issue with populating some fields in a Kendo Grid.

I have a page that displays details about a Team. On that page is a Kendo grid that displays a list of members in the current team that is being viewed. The grid has the following columns

Username
FirstName
LastName
EffectiveFromDate
EffectiveToDate

The page can be put into an edit state which allows you to then edit or delete team members in the grid using edit or delete buttons in each row of the grid. There is also top level option to add a new member to the team.

When i click on the new button to add a new member, a popup is displayed. On the popup is an autocomplete list for selecting who is to be added to the team, and two datetime pickers for the effective to and from dates.

When i select a user from the autocomplete, enter the effective to and from dates, and click Ok to close the popup, a new row is added to the grid as expected. But the Username, First Name and Last Name fields are not populated.

I have added hidden fields onto the popup view that are populated on an onUserAutoCompleteChanged event in the AutoComplete view. When i debug i can see these fields are being correctly populated with the correct data when i make a user selection with the autocomplete. The issue is that the data is not being re-bound to the grid when i close the popup.

I added a text field for FirstName to the popup so i could see that it was being populated when i made a selection in the autocomplete, which it definitely is.

If i make a user selection without making any changes to the First Name text field and close the popup, the data is not displayed in the grid although a new row is created. However, if i select a user from the autocomplete to populate the FirstName text field and then alter the text in that field, and then close the popup, the data is displayed in the grid for FirstName.

How do i go about firing whatever is causing the data to bind to the grid when i update the text field without having to update the text field?

TeamPage cshtml
<div class="row">
    <div class="form-group  col-md-6 ">
        @Html.LabelFor(model => model.TeamCode)
        @Html.EditorFor(model => model.TeamCode)
        @Html.ValidationMessageFor(model => model.TeamCode)
    </div>
</div>
<div class="row">
    <div class="form-group  col-md-6 ">
        @Html.LabelFor(model => model.TeamName)
        @Html.EditorFor(model => model.TeamName)
        @Html.ValidationMessageFor(model => model.TeamName)
    </div>
</div>
<div class="row">
    <div class="form-group  col-md-12 ">
        @Html.LabelFor(model => model.TeamDesc)
        @Html.EditorFor(model => model.TeamDesc)
        @Html.ValidationMessageFor(model => model.TeamDesc)
    </div>
</div>
<div class="row">
    <div class="form-group col-md-12">
        @Html.Partial("~/Areas/Teams/Views/TeamMember/_List.cshtml", this.Model.Members, null)
        @Html.ValidationMessageFor(model => model.Members)
    </div>
</div>
  
<script type="text/javascript">
  
    function buildData() {
        // Get the form values into simple key value array
        var formData = getFormObj();
        var gridData = $("#teamMemberGrid").data("kendoGrid").dataSource.data();
  
        // Prepare the model
        return {
            TeamDetailId: formData["TeamDetailId"],
            TeamCode: formData["TeamCode"],
            TeamDesc: formData["TeamDesc"],
            TeamName: formData["TeamName"],
            Members: gridData,
            Dto: formData["Dto"]
        };
    }
  
    $(function () {
        $("form").on("submit", function (event) {
            event.preventDefault();
            var request = buildData();
            submitForm(request, this.action);
        });
    });
  
</script>

TeamMemberGrid cshtml
<div>
    @(Html.AjaxGridFor<TeamMemberModel>("teamMemberGrid", "Teams", "TeamMember")
        .ToolBar
        (
            toolbar =>
            {
                if (Html.ShowEditControls())
                {
                    toolbar.Template("<a class='k-button k-button-icontext ' href='' id='customGridAdd'><span></span>New</a><span></span>");
                }
            }
        )
        .Columns
        (
            columns =>
            {
                if (Html.ShowEditControls())
                {
                    columns.Command(commands =>
                    {
                        commands.Custom("Edit").Text("Edit").Click("onGridEdit");
                        commands.Custom("Delete").Text("Delete").Click("onGridDelete");
                    });
                }
            }
        )
        .BuildAjaxDataSource<TeamMemberModel>("TeamMember", updateAction: "UpdateMember", createAction: "AddMember", destroyAction: "RemoveMember")
    )
 
    <script type="text/javascript">
 
        function onGridEditing(e) {
            var id = $('#TeamDetailId').val();
            if (e.model.isNew()) {
                e.model.set("TeamDetailId", id);
                e.model.set("TeamMemberId", kendo.guid());
            }
            setPopupTitle(e);
            setGridPopupButtons(e);
        }
 
        //set username, first name, last name
        function onGridSaving(e) {
            var data = e.sender.dataSource.data();
            for (var i = 0; i < data.length; i++) {
                var item = data[i];
                if (item.TeamMemberId === e.model.TeamMemberId) {
                    item.set('Username', $('Username').val());
                }
            }
        }
 
        function onGridDelete(e) {
            var grid = $("#teamMemberGrid").data("kendoGrid");
            var row = $(e.currentTarget).closest("tr");
            grid.removeRow(row);
        }
 
    </script>
</div>

Popup View cshtml
<div class="form-group col-md-11">
    @Html.LabelFor(model => model.UserDetailId)
    @Html.EditorFor(model => model.UserDetailId)
    @Html.ValidationMessageFor(model => model.UserDetailId)
</div>
 
<div class="form-group col-md-11">
    @Html.LabelFor(model => model.EffectiveFromDate)
    @Html.EditorFor(model => model.EffectiveFromDate)
    @Html.ValidationMessageFor(model => model.EffectiveFromDate)
</div>
 
<div class="form-group col-md-11">
    @Html.LabelFor(model => model.EffectiveToDate)
    @Html.EditorFor(model => model.EffectiveToDate)
    @Html.ValidationMessageFor(model => model.EffectiveToDate)
</div>
 
<div class="form-group col-md-11">
    @Html.LabelFor(model => model.FirstName)
    @Html.EditorFor(model => model.FirstName)
    @Html.ValidationMessageFor(model => model.FirstName)
</div>
@Html.HiddenFor(model => model.TeamMemberId)
@Html.KendoScripts()
 
 
<input id="Username" name="Username" data-val="true" data-bind="value:Username" type="hidden" value="">
<input id="FirstName" name="FirstName" data-val="true" data-bind="value:FirstName" type="hidden" value="">
<input id="LastName" name="LastName" data-val="true" data-bind="value:LastName" type="hidden" value="">

AutoComplete cshtml
    function onUserAutoCompleteChange(e) {
        var dataItem = $("#@this.ViewData.ModelMetadata.PropertyName").data("kendoDropDownList").dataItem();
 
        $("#Username").val(dataItem.Username);
        $("#FirstName").val(dataItem.FirstName);
        $("#LastName").val(dataItem.LastName);
    }
</script>

TeamMemberController
/// <summary>
/// For use with Kendo Grid ajax binding
/// Creates new models by inserting the data posted by the Kendo Grid into the grid datasource.
/// </summary>
/// <param name="products">The model created by the user.</param>
/// <returns>The inserted model so the Kendo Grid is aware of the newly generated model</returns>
[HttpPost]
public virtual ActionResult AddMember([DataSourceRequest]DataSourceRequest request, TeamMemberModel model)
{
    return Json(new[] { model }.ToDataSourceResult(request, ModelState));
}

Thanks in advance
Michael
Top achievements
Rank 1
 answered on 15 Sep 2014
1 answer
188 views
I wish I could get as far as all the other users having issues with formatting dates, but I'm stuck right here. The Format method isn't working. My grid is still displaying a Json date looking like this /Date(1364927400000)/. My date field is actually a DateTimeOffset field and I really would rather use a format string like yyyy-MM-dd hh:mm:ss tt K or yyyy-MM-dd hh:mm:ss tt zzz, but /Date(1364927400000)/ is completely unacceptable.


​ @(Html.Kendo().Grid<UtiliPoleOfficeWeb.Models.JobPriorityModel>()
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.Id).Hidden(true);
columns.Bound(p => p.Description).Width(150);
columns.Bound(p => p.Priority).Width(100);
columns.Bound(p => p.Owner).Width(100);
columns.Bound(p => p.Started).Format("{0:dd/MM/yyyy}");
columns.Bound(p => p.Inspector).Width(150);
columns.Bound(p => p.Completed).Width(425).Format("{0:dd/MM/yyyy}");
columns.Bound(p => p.FRInspector).Width(140).Title("Field Review Inspector");
columns.Bound(p => p.FRCompleted).Width(425).Title("Field Review Completed");
columns.Command(command => { command.Edit(); }).Width(100);
}) . . .

Please help.

Kiril Nikolov
Telerik team
 answered on 15 Sep 2014
3 answers
143 views
Hi,

I am trying to call a Html extension helper method  'GetUserFormattedId' from the client template of  a ajax bound grid column. I am trying the format a value of the column.

I am unable to get it working. Is it allowed to call extension methods in this way? Please advise. 

@{
          Html.Kendo().Grid<InvoiceSummaryDto>()
          .Name("invoiceAccountingGrid")
          .Columns(columns =>
          {
              columns.Bound(l => l.Id).ClientTemplate("<a href='" + @Url.Action("Details", "Invoice", new { area = "Accounting" }) + "/#= Id #'" + ">" + @Html.GetUserFormattedId(@"#= Id #") + "</a>").Title("ID");
              columns.Bound(l => l.ItemsDescription).Title("Description");
                    
          })

I
Dimiter Madjarov
Telerik team
 answered on 15 Sep 2014
3 answers
496 views
Hello, I need to check if the Window is already init, if possible. 

Do you know if there is a good way to know this ? Without use a parameter in my controller would be best.

Thanks
Dimiter Madjarov
Telerik team
 answered on 15 Sep 2014
5 answers
534 views
I would like to use inline editing with KendoUI grids in an MVC context, but can't at the moment for any data containing Date fields, because whenever I click the Update button (whether after creating a new record, or editing an existing one), even if I haven't changed the date field, I get a validation error (e.g. if the field is DateOfBirth)

"The field Date of Birth must be a date". (please see attached screenshot)

The date format I am setting for the Grid is dd MMM yyyy (because this is unambigous, whereas e.g 04 06 2012 is ambiguous and could mean either 4 June 2012 or 6 April 2012) and my pc (Windows 8, running Visual Studio 2012) is set up with UK regional settings.

(I have a support ticket set up for this, but no solution yet after 10 days), so am posting it here in case anyone else can help.

NB It has been suggested that I set the culture to "en-GB" (which I have never had to do before, including lots of other [non inline editing] use of KendoUI grids), but it didn't resolve the problem.

Thanks in advance for your help
Patrick
Top achievements
Rank 2
 answered on 12 Sep 2014
9 answers
166 views
How can I add a Color Picker to the event dialog using resources?  I even looked at a custom editor but recreating the stock event dialog seems like it will be complex just to add a Color Picker.

Is there a demo for this?

​
.Resources(resource =>
    {
        resource.Add(m => m.Color)     // Need this to be a color picker
            .Title("Color")
            .DataTextField("Name")
            .DataValueField("ColorID")
Petur Subev
Telerik team
 answered on 12 Sep 2014
1 answer
1.6K+ views
I can't seem to get the change event to fire. 

Here's the code:

<div class="k-edit-label">
    @(Html.LabelFor(model => model.IsAllDay))
</div>
<div data-container-for="isAllDay" id="is-all-day" class="k-edit-field">
    <input data-bind="checked: isAllDay" data-val="true" id="isAllDay" name="isAllDay" type="checkbox" />
</div>

I've tried:

$(function () {
    $("#isAllDay").change(function () {
        alert("changed changed");
    });
});

and

<div class="k-edit-label">
    @(Html.LabelFor(model => model.IsAllDay))
</div>
<div data-container-for="isAllDay" id="is-all-day" class="k-edit-field">
    <input data-bind="checked: isAllDay, events: { change: isAllDayChanged}" data-val="true" id="isAllDay" name="isAllDay" type="checkbox" />
</div>
function isAllDayChanged() {
    alert("changed");
}

What am I missing?
Vladimir Iliev
Telerik team
 answered on 12 Sep 2014
4 answers
95 views
Hi,

I would like to use the scheduler control to create a perpetual week calendar.
I would be a full week without dates.
Then I don't need all the buttons around the calendar.

Is that possible ?

Regards,

David
David
Top achievements
Rank 1
 answered on 11 Sep 2014
19 answers
737 views
Hi All.  Trying to use Cascading DropDown inside a grid "in-line" edit mode. The initial values are not being set for edit mode.  Add mode is working as expected.  I tried some jQuery  to set these manually but that did not work either.

So two problems:  

1. Why aren't the initial values set during edit mode properly?
2. Why does this code fail to change the value of the dropdown - control.value("1");

Thanks
-Jonathan





Here is the Jquery/JS I used:
<script>
    function SelectedCedingCompany() { return { CedingCompanyId: $("#CedingCompanyId").val() }; }
    function SelectedCedingCompanyLine() { return { CedingCompanyLineId: $("#CedingCompanyLineId").val() }; }
 
    function CoveredLinesAndSublinesGridBeginEdit(e)
    {
        var control = e.container.find('#CedingCompanyStateId').data('kendoDropDownList');
        control.enable();
        control.value("1");
    }
</script>


My Grid looks like this:
@(Html.Kendo().Grid<ContractScope>()
    .Name("CoveredLinesAndSublinesGrid")
    .Columns(columns =>
    {
        columns.ForeignKey(c => c.CedingCompanyId, (System.Collections.IEnumerable)ViewBag.CedingCompanies, "CedingCompanyId", "CompanyName")
            .Width(100).Title("Ceding Company")
            .EditorTemplateName("Contract/ContractScopeCedingCompanyDropDown");
         
        columns.ForeignKey(c => c.CedingCompanyStateId, (System.Collections.IEnumerable)ViewBag.CedingCompanyStates, "CedingCompanyStateId", "CedingCompanyStateDescription")
            .Width(50).Title("State")
            .EditorTemplateName("Contract/ContractScopeCedingCompanyStateDropDown");
 
        columns.Command(command => { command.Custom("Edit").SendDataKeys(true); command.Edit(); }).Width(150);
    })
    .ToolBar(tb => tb.Template(
    @<text>
    <a class='k-button k-button-icontext k-grid-add ActionButton' href="#" style="padding-top:2px; padding-bottom:4px;">
        <span class="k-icon k-add"></span>Add Covered Line / Sublines
    </a>
    </text>))
    .Scrollable(s=>s.Height(300))
    .Editable(editable => editable.Mode(GridEditMode.InLine))
    .Events(events => events.Edit("CoveredLinesAndSublinesGridBeginEdit"))
    .DataSource(dataSource => dataSource
        .Ajax()       
        .Filter(filter => filter.Add(e => e.ContractId).IsEqualTo(contractID))
        .Events(events => events.Error("AjaxFailure"))
        .Model(model =>
        {
            model.Id(p => p.ContractScopeId);
            model.Field(p => p.ContractId).Editable(false);
            model.Field(p => p.ContractScopeId).Editable(false);
            model.Field(p => p.CedingCompanyId);
            model.Field(p => p.CedingCompanyStateId);
        })       
        .Read(read => read.Action("Read", "CoveredLines", new { area = "Contract" }).Type(HttpVerbs.Post))
        .Create(create => create.Action("New", "CoveredLines", new { area = "Contract", id = contractID }).Type(HttpVerbs.Post))
        .Update(update => update.Action("Update", "CoveredLines", new { area = "Contract" }).Type(HttpVerbs.Post))
        .PageSize(20)
    )   
)
My Templated  DropDown Editors:
@(Html.Kendo().DropDownList()
    .HtmlAttributes(new { id = "CedingCompanyId"})
    .DataTextField("CompanyName")
    .DataValueField("CedingCompanyId")
    .Name("CedingCompanyId")
    .DataSource(source => source
        .Read(read => read.Action("GetCedingCompanies", "CoveredLines", new { area = "Contract" })
        .Type(HttpVerbs.Post))
        .ServerFiltering(true)))

@(
    Html.Kendo().DropDownList()
    .HtmlAttributes(new { id = "CedingCompanyStateId"})
    .DataTextField("CedingCompanyStateDescription")
    .DataValueField("CedingCompanyStateId")
    .Name("CedingCompanyStateId")
    .DataSource(source => source
        .Read(read => read.Action("GetCedingCompanyStates", "CoveredLines", new { area = "Contract" })
            .Type(HttpVerbs.Post)
            .Data("SelectedCedingCompany"))
        .ServerFiltering(true))
    .Enable(true)
    .AutoBind(false)
    .CascadeFrom("CedingCompanyId")
)
Rick
Top achievements
Rank 1
 answered on 11 Sep 2014
2 answers
142 views
I'm having trouble binding a stacked bar chart to a local Model.

If I keep the data inline in the Razor file, all works fine (see attached Inline.png for the results):

<div class="chart-wrapper">
    @(Html.Kendo().Chart(Model.SeriesData)
        .Name("chart")
        .Title("Test Chart")
        .Legend(legend => legend
            .Visible(false)
        )
        .SeriesDefaults(seriesDefaults =>
            seriesDefaults.Bar().Stack(ChartStackType.Normal)
        )
        .CategoryAxis(axis => axis
            .Categories("Bob Jones", "Sarah Giant")
            .MajorGridLines(lines => lines.Visible(false))
        )
        .ValueAxis(axis => axis
            .Numeric()
            .Line(line => line.Visible(false))
            .MajorGridLines(lines => lines.Visible(true))
        )
        .Series(series =>
        {
            series.Bar(new double[] { 10, 17 }).Color("#f3ac32");
            series.Bar(new double[] { 30, 27 }).Color("#b8b8b8");
            series.Bar(new double[] { 10, 17 }).Color("#e3ac32");
            series.Bar(new double[] { 30, 27 }).Color("#ab6e36");
        })
        .Tooltip(tooltip => tooltip
            .Visible(true)
            .Template("#= series.name #: #= value #")
        )
    )
</div>

However, if I move the data to a model, it seems to bind incorrectly (See attached bound.png for the results):

@model LyncMeetingReporting.Report.Controllers.ChartModel
<div class="chart-wrapper">
    @(Html.Kendo().Chart(Model.SeriesData)
        .Name("chart")
        .Title("Test Chart")
        .Legend(legend => legend
            .Visible(false)
        )
        .SeriesDefaults(seriesDefaults =>
            seriesDefaults.Bar().Stack(ChartStackType.Normal)
        )
        .CategoryAxis(axis => axis
            .Categories(Model.Attendees)
            .MajorGridLines(lines => lines.Visible(false))
        )
        .ValueAxis(axis => axis
            .Numeric()
            .Line(line => line.Visible(false))
            .MajorGridLines(lines => lines.Visible(true))
        )
        .Series(series =>
        {
            series.Bar(m => m.Data, m => m.Colour);
        })
        .Tooltip(tooltip => tooltip
            .Visible(true)
            .Template("#= series.name #: #= value #")
        )
    )
</div>

The model:

public ActionResult Log(Guid? id, MeetingDetailsType? type)
{
    var chartModel = new ChartModel() {
        Attendees = new string[] { "Bob Jones", "Sarah Giant" },
        SeriesData = new SeriesData[]
        {
            new SeriesData() { Colour = "#f3ac32", Data = new double[] { 10, 17 }},
            new SeriesData() { Colour = "#b8b8b8", Data = new double[] { 30, 27 }},
            new SeriesData() { Colour = "#e3ac32", Data = new double[] { 10, 17 }},
            new SeriesData() { Colour = "#a8b8b8", Data = new double[] { 30, 17 }},
        }
    };
 
    return View(chartModel);
}
 
public class ChartModel
{
    public IEnumerable<string> Attendees { get; set; }
    public IEnumerable<SeriesData> SeriesData { get; set; }
}
 
public class SeriesData
{
    public double[] Data {get; set;}
    public string Colour {get; set; }
}

Paul Nearney
Top achievements
Rank 1
 answered on 11 Sep 2014
Narrow your results
Selected tags
Tags
+? more
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Rob
Top achievements
Rank 3
Iron
Iron
Iron
Atul
Top achievements
Rank 1
Iron
Iron
Iron
Alexander
Top achievements
Rank 1
Veteran
Iron
Serkan
Top achievements
Rank 1
Iron
Shawn
Top achievements
Rank 1
Iron
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?