Telerik Forums
UI for ASP.NET MVC Forum
1 answer
31 views

I'm having an issue with a Grid component.  I have 2 custom editors for 2 small dropdown lists.  Anytime I select anything other than the default options for either (or both) dropdown lists, the default still gets assigned to the field for some reason.  I've tried debugging but it seems that it's getting changed before anything is sent to the controller (defaults are already present in the post action).

I set the custom editors up using the instructions here.

This is the component itself

@(
Html.Kendo().Grid<CHAASAddInsuredsViewModel>()
.Name("AddlInsureds")
.Columns(columns =>
{
columns.Bound(c => c.FirstName).Width(130);
columns.Bound(c => c.MiddleInitial).Width(70);
columns.Bound(c => c.LastName).Width(150);
columns.Bound(c => c.DOB).Format("{0:MM/dd/yyyy}").Width(150);
columns.Bound(c => c.RelationshipType)
.ClientTemplate("#=RelationshipType.RelationshipName#")
.EditorTemplateName("RelationshipTypeEditor").Width(140);
columns.Bound(c => c.Gender)
.ClientTemplate("#=Gender.GenderName#")
.EditorTemplateName("GenderEditor").Width(150);
columns.Bound(c => c.SSN).Width(160)
.HtmlAttributes(new { @class = "text-center" });
@* .EditorTemplateName("SSNEditorTemplate"); *@
@* .ClientTemplate("<h4>XXX-XX-XXXX</h4>"); *@
columns.Command(c => { c.Edit(); c.Destroy(); });
}
)
.ToolBar(toolbar => toolbar.Create().Text("Add Family Member"))
.Editable(editable => editable.Mode(GridEditMode.InLine)
.ConfirmDelete("Continue to delete this record?")
.DisplayDeleteConfirmation("Continue to delete this record?"))
.Sortable()
.Scrollable()
@* .HtmlAttributes(new { style = "height:550px;" }) *@
.DataSource(d => d
.Ajax()
.Model(m =>
{
m.Id(i => i.Id);
m.Field(f => f.RelationshipType)
.DefaultValue(ViewData["defaultRelationshipType"] as HNL_Agents.Models.AddlInsuredRelationshipType);
m.Field(f => f.Gender)
.DefaultValue(ViewData["defaultGender"] as HNL_Agents.Models.AddlInsuredGender);
})
.Events(e => e.Error("error_handler"))
.Create(c => c.Action("Insured_CreateUpdate", "CHAAS", new { modelAppId = Model.AppId }))
.Read(r => r.Action("GetInsureds", "CHAAS", new { modelAppId = Model.AppId}))
.Update(c => c.Action("Insured_CreateUpdate", "CHAAS", new { modelAppId = Model.AppId }))
.Destroy(d => d.Action("RemoveInsureds", "CHAAS"))
)
)

 

My model is as follows.

public class CHAASAddInsuredsViewModel
{

[AllowNull]
[ScaffoldColumn(false)]
[HiddenInput]
public int? Id { get; set; }

[AllowNull]
[ScaffoldColumn(false)]
[HiddenInput]
public int? AppId { get; set; }


[UIHint("RelationshipTypeEditor")]
[Display(Name ="Relationship Type")]
public AddlInsuredRelationshipType RelationshipType { get; set; }

[Required]
[StringLength(35)]
[Display(Name = "Last Name")]
public string LastName { get; set; }

[Required]
[StringLength(35)]
[Display(Name = "First Name")]
public string FirstName { get; set; }

[AllowNull]
[Display(Name = "M.I.")]
[RegularExpression("^[a-zA-Z]$", ErrorMessage = "Middle Initial must be only 1 letter")]
public string? MiddleInitial { get; set; }

//public int Age { get; set; }

[Required]
[Display(Name = "Birth Date")]
[DataType(DataType.Date)]
[CHAASChildMaxAge(26, ErrorMessage = "The maximum age for a child is 26.")]
public DateTime DOB { get; set; }


[UIHint("GenderEditor")]
public AddlInsuredGender Gender { get; set; }

[Required]
[Display(Name = "Social Security #")]
[StringLength(9)]
//[UIHint("SSNEditorTemplate")]
[RegularExpression(@"^\d{9}|[1-9]{2}\d{1}-\d{2}-\d{4}$", ErrorMessage = "Invalid Social Security Number")]
public string SSN { get; set; }
}

 

These are the custom editors for the drop down lists

@(
Html.Kendo().DropDownList()
.Name("RelationshipType")
.DataValueField("RelationshipId")
.DataTextField("RelationshipName")
.BindTo((System.Collections.IEnumerable)ViewData["relationshipTypes"])
)

 

@(
Html.Kendo().DropDownList()
.Name("Gender")
.DataValueField("GenderId")
.DataTextField("GenderName")
.BindTo((System.Collections.IEnumerable)ViewData["genders"])
)

 

 

Please let me know if there is anything I'm missing or if you need any more information.  Thanks for the help!

Anton Mironov
Telerik team
 answered on 04 Apr 2024
1 answer
39 views

I'm using a k-grid with an items per page dropdown, it initially loads correctly but when a new value is selected then the pager elements are hidden. 

Anton Mironov
Telerik team
 answered on 25 Oct 2023
1 answer
293 views


@model DetailSelectionViewModel

@(Html.Kendo().DropDownListFor(m => m)
        .DataValueField("Id")
        .DataTextField("Name")
        .Value(Model.Selected)
        .Events(e =>
        {
            e.Select("SelectionDropDownItemSelected");
            e.DataBound("SelectionDropDownDataBound");
        })
        .DataSource(dataSource => dataSource
            .Read(read => read.Action("GetDetailList", "DataWorksheet"))
        )
)

Above is the drop down that I have embedded within a detail grid.  When a value is changed in the master grid I need to traverse through all the detail rows and change the selected item in the dropdown list in each row.

So I successfully traverse the dataitems bound to the detailgrid. The dropdown appears to be changed until you actually click on the dropdown list and the dropdown appears with the selecteditem still being the item that was selected when the grid was originally rendered. When I click on the dropdown the Read Action occurs and the data is retrieved and the dropdown is bound, but the selected value isnt set to the new value desired.

Thinking that I can traverse the dataitems and set the values there. Think I need to traverse the datagrid itself and find the dropdown list in each row and programmatically choose the selected value.  I see no sample code to one traverse the datagrid that is a child when parent changed. I see no sample code to find the dropdown list in a datagrid row.

My logic starts when the datasource change event occurs for the parent grid.

Can anyone assist please. These tasks cant be that uncommon.

Anton Mironov
Telerik team
 answered on 27 Sep 2023
1 answer
168 views

Hi,

I am working on a grid having inline edit functionality.  I am trying to create a dropdown which display a list of persons, however, I want to save the email id of the person in our backend SQL DB.

I am trying to implement this with editor template approach -

I have tried the below code -

Grid:

columns.Bound(mm => mm.Person).Title("Assigned To").EditorTemplateName("PersonList").HeaderHtmlAttributes(new { style = "white-space: normal" });

PersonList.chstml

@(Html.Kendo()
            .DropDownList()
            .Filter("contains")
            .Name("Person")
            .DataTextField("Name")
            .DataValueField("Email")
            .DataSource(dataSource =>
            {
                dataSource.Read(read => read.Action("GetPeopleByArea", "Common").Data("getPeopleByArea"))
                .ServerFiltering(true);
            })
            //.HtmlAttributes(new { required = "required", data_required_msg = "Select Person Name", style = "width: 100px" })
            .ValuePrimitive(true)
            .AutoWidth(true)
            .OptionLabel("-- Please Select --")            
    )

 

function getPeopleByArea() {
        var grid = $("#Grid").data("kendoGrid");
        var dataItem = grid.dataItem("tr.k-grid-edit-row");
        return {
            Area: dataItem.Area
        };
    }

When I edit the grid the dropdown work list works fine and it displays the filtered list of people as expected.  However, Instead of the email id the record is getting updated with Null or blanks in the backend table.

However, this approach works fine if I do not use getPeopleByArea function to filter the area based on certain conditions and use a different controller function to get the whole list.

Also, if I am using  .DataTextField("Name") and  .DataValueField("ID"), ID is getting stored and same is getting displayed on the grid instead of the Name.

What am I doing wrong here ? Can anyone please suggest.

Please let me know if you have any questions.

 

 

Thanks

Saurabh

 

Saurabh
Top achievements
Rank 1
Iron
 answered on 07 Aug 2023
1 answer
215 views

Hello,

I am struggling with why my Save button on my Kendo Grid is not calling my update action (inline edit mode).  The edit column uses a dropdown list editor template.  The dropdown list editor fills fine with my values and I can select one.  But when I click the Save button (from toolbar) it does not call my add function in the controller.  I see no errors in F12 utility.  Any help is appreciated as I've been struggling with this all day.

Here is my relevant code:

Edit Grid:

<style>
    .k-grid-content td {
        position: relative;
    }

    .k-grid .k-grid-header .k-header .k-link {
        height: auto;
    }

    .k-grid .k-grid-header .k-header .k-column-title .k-header {
        white-space: normal;
    }
</style>
@{
    ViewData["Title"] = "Administration";
}

<div style="margin-left:10px; margin-top:10px">
<div>Manage Assignees</div>
<div class="row" style="margin-top:10px">
    <div class="col-auto">
            @(
                    Html.Kendo().Grid<Assignees>()
                    .Name("grid")
                    .Width("250px")
                    .Columns(columns =>
                    {
                        columns.Bound(p => p.SortName).Width(130).Title("Assignee").EditorTemplateName("AssigneesAdd");
                    })
                    .Sortable(true)
                    .Navigatable()
                    .Scrollable(scr => scr.Height(200))
                    .Editable(editable => editable.Mode(GridEditMode.InLine))
                    .Selectable()
                    .AutoBind(true)
                    .ColumnMenu(false)
                    .ToolBar(tb =>
                    {
                        tb.Create().Text("New");
                        tb.Save().Text("Save").CancelText("Cancel");
                    })
                    .DataSource(dataSource => dataSource
                    .Ajax()
                    .Read(read => read.Action("GetAssigneesForAddGridDisplay", "Home").Type(HttpVerbs.Post))
                    .Update(update => update.Action("AddAssigneeRecord", "Home").Type(HttpVerbs.Post))
                    .Destroy(destroy => destroy.Action("DeleteAssigneeRecord", "Home").Type(HttpVerbs.Post))
                    .Events(e => e.Error("onError"))
                    .Batch(false)
                    .Model(model =>
                    {
                        model.Id(p => p.SortName);
                        model.Field(p => p.SortName);
            })
            )
            .Deferred()
            )
    </div>
</div>
</div>
@section Scripts{
    @Html.Kendo().DeferredScripts()

    <script>
        $(document).ready(function () {
        });

        function onError() {
        @*window.location='@Url.Action("Index", "Error")';*@
                }

    </script>

}

===============================================

Controller Add Function called by .Update event in grid

  [HttpPost]
        public async Task<ActionResult> AddAssigneeRecordAsync([DataSourceRequest] DataSourceRequest request, SelectListItem assigneeRecord)
        {

            try
            {
                await _dataService.AddAssigneeRecordAsync(assigneeRecord);

                return Json(await new[] { assigneeRecord }.ToDataSourceResultAsync(request, ModelState));
            }
            catch (Exception ex)
            {
                await _dataService.LogExceptionAsync("HomeController", "AddAssigneeRecordAsync", _username, ex);
                return BadRequest();
            }
        }

===============================================

DropDownList editor template("AssigneesAdd"):

@using Estimating_State_Licensing_Certification.Controllers
@using Kendo.Mvc.UI
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Kendo.Mvc
@model string;

@(Html.Kendo().DropDownListFor(m => m)
        .DataValueField("Text")
        .DataTextField("Text")
        .Filter("startswith")
        .OptionLabel("Select an Employee")
        .DataSource(source =>
        {
            source.Read(read =>
            {
                //this is the edit template used for the Admin assignee grid for adding NEW assignees
                read.Action("GetAssigneesForAdminAdd", "Home").Type(HttpVerbs.Post);
            });
        })
)

==============================================

"Assignees" class/entity used by the grid

   public class Assignees
    {
        public string? SortName { get; set; } = string.Empty;
    }

 

Thanks!

Acadia

Aleksandar
Telerik team
 answered on 25 Apr 2023
5 answers
368 views

Hello everyone,

I have a little problem with editing my grid and I hope you can help me.

I am currently developing a grid (Telerik UI for ASP.NET MVC Grid) in which you can open another grid using a button at the end of the row. In this second grid it is possible to select one or more employees (Inline Editing with a DropDown) for the previous entry. In addition to the actual employee, there is another column where you can set a checkbox to "true" or "false". You can create a new entry with the button on the top left and you can edit or delete it with the two buttons on the right in the line.

Now to my question: My plan is that the name of the employee can only be changed when creating the entry. If you click on Edit, the name should no longer be editable, only the checkbox should be.

How exactly do I do this?

I had the idea to set the field "UserId" to .Editable(false) under .Model. But if I do that, I can neither change the value when creating nor when editing. When creating the entry, the drop-down menu for selecting an employee should be available, but not when editing.

In the attachments I have pictures showing the grid exactly.

Thanks in advance
Lars

 

@(Html.Kendo().Grid(Model)
    .Name("AssignmentsGrid")
    .Columns(c =>
    {
        c.ForeignKey(m => m.UserId, (IEnumerable) ViewData["users"], "Id", "Name").EditorTemplateName("ProjectUserDropdown");
        c.Bound(m => m.Resigned).ClientTemplate("<input type='checkbox' #= Resigned ? checked='checked' :'' # disabled='disabled' />");
        c.Command(command =>
        {
            command.Edit();
            command.Destroy();
        });
    })
    .ToolBar(t => t.Create())
    .Events(events =>
    {
        events.Edit(@<text>function(e) { if(e.model.isNew()) { e.model.set('ProductionOrderId', @ViewData["productionOrderId"]); } else { $('[name="ProjectManagerId"]').attr("readonly", true); }} </text>);
    })
    .DataSource(s => s
        .Ajax()
        .Create(c => c.Action("UserAssignmentAdd", "ProductionOrder", new {area = "Sktcrm"}))
        .Read(r => r.Action("UserAssignmentRead", "ProductionOrder", new {area = "Sktcrm"}).Data(@<text>function(e) { return { productionOrderId: @ViewData["productionOrderId"] }; }</text>))
        .Update(u => u.Action("UserAssignmentUpdate", "ProductionOrder", new {area = "Sktcrm"}))
        .Destroy(d => d.Action("UserAssignmentDelete", "ProductionOrder", new {area = "Sktcrm"}))
        .Model(m =>
        {
            m.Id(model => model.UserId);
            //m.Field(t => t.UserId).Editable(false);
        })
        .ServerOperation(false))
    .Scrollable()
    .Sortable()
    .Filterable())


Eyup
Telerik team
 answered on 27 Jan 2023
1 answer
101 views

I have had to admit defeat after much googling and trial and error I have been unable to recreat what I want.

I have a view model that can be simplified as follows;

    public class HeadsOfClaim
    {
        public HeadsOfClaim()
        {

        }

        public int? ClaimId { get; set; }
        public int? ClaimDetailId { get; set; }
        public string ClaimType { get; set; }
        public string Description { get; set; }
        public bool Rejected { get; set; }
    }

A controller which returns the json

    public ActionResult ReturnHeads([DataSourceRequest]DataSourceRequest request, int? id)
    {
        Claim c = db.Claims.Find(id);
        IEnumerable<HeadsOfClaim> details = ViewModels.HeadsOfClaim.GetList(c);
        return Json(details.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
    }

and a view that includes the following

    @(Html.Kendo().Grid<ClaimRegister.ViewModels.HeadsOfClaim>()
        .Name("Grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.ClaimType).Filterable(ftb => ftb.Cell(cell => cell.Operator("contains").SuggestionOperator(FilterType.Contains)));
            columns.Bound(p => p.Description).Filterable(ftb => ftb.Cell(cell => cell.ShowOperators(false))).Width(225);
            columns.Template(@<text></text>).HtmlAttributes(new { @class = "templateCell", id = "#=id#" }).ClientTemplate(
                Html.Kendo().DropDownButton()
                    .Name("menu_TEST_#=id#")
                    .Text("Action")
                    .Size(ComponentSize.Large)
                    .Items(its =>
                    {
                        its.Add().Text("Reverse Rejection").Hidden("#=Rejected#" == "true").HtmlAttributes(new { data_id = "#=id#" }).Click("ConfirmUnReject");
                        its.Add().Text("--Set").Hidden("#=Rejected#" != "true").Enabled(false);
                        its.Add().Text("Reserve").Hidden("#=Rejected#" != "true").HtmlAttributes(new { data_title = "Set Reserve", data_url = Url.Action("Individual", "Reserve", new { type = type, id = "#=id#" }) }).Click("LaunchModal");
                        its.Add().Text("Settlement").Hidden("#=Rejected#" != "true").HtmlAttributes(new { data_title = "Set Settlement", data_url = Url.Action("Individual", "Settlement", new { type = type, id = "#=id#" }) }).Click("LaunchModal");
                        its.Add().Text("--View").Enabled(false);
                        its.Add().Text("Allocation").HtmlAttributes(new { data_title = "Review Allocation", data_url = Url.Action("Review", "Allocation", new { id = "#=id#" }) }).Click("LaunchModal");
                    })
                    .ToClientTemplate().ToHtmlString()
            );
        })
        .Pageable()
        .Sortable()
        .Groupable()
        .Events(ev => ev.DataBound("initMenu"))
        .Filterable(ftb => ftb.Mode(GridFilterMode.Row))
        .DataSource(dataSource => dataSource
            .Ajax()
            .Model(m => {
                m.Id(d => d.ClaimDetailId);
                m.Field(d => d.Rejected);
            })
            .Group(groups => groups.Add(p => p.ClaimType))
            .Read(read => read.Action("ReturnHeads", "ClaimDetails", new { id = id }))
        )
    )

...

<script>
    function initMenu(e) {
        $(".templateCell").each(function () {
            eval($(this).children("script").last().html());
        });
    }
</script>

My problem is setting the visibility of the dropdown options.  Effectively dependent on whether the claim is Rejected (true or false) I want different options to be available to the user. 

I had a look at the template script before initMenu runs but the evaluation is already made by that stage so it is unclear how it is doing the checking.

Irrelevant of whether rejected is true or false I get "Reverse Rejection", "--View" and "Allocation" as the only visible option.

Any help or insights gratefully received.

Ivan Danchev
Telerik team
 answered on 06 Jan 2023
1 answer
1.0K+ views

In CSP we were using script-src 'self' 'unsafe-inline' 

but for security purpose need to remove 'unsafe-inline' , we added  'nonce-a9f04fd1-06cf-4948-9d66-ea306e581896' for inline script.

applied nonce for inline script 

<script type="text/javascript" nonce="a9f04fd1-06cf-4948-9d66-ea306e581896">

</script>

but after applying these change kendo  controls not working. Our assumption is there are dynamic inline scripts generated  for kendo controls which not contains nonce. so it may cause an issue.

we also tried DeferredScripts but no success. after applying 'unsafe-inline'  it works.

<script type="text/javascript" nonce="a9f04fd1-06cf-4948-9d66-ea306e581896">

    @Html.Kendo().DeferredScripts()

</script>

 

Please suggest as we want to remove 'unsafe-inline' with kendo controls need to work.

 

Ivan Danchev
Telerik team
 answered on 16 Dec 2022
2 answers
81 views

Dears

I'm facing this problem: in an MVC Grid, setted with InCell editing, I have a Foreign Key column. When I edit the FK cell the DDL is not showed.

I checked the documentation and for me it is all ok. 

Here some details:

[GRID DEFINITION]

        @(Html.Kendo().Grid<MCP310.Models.MCP_Detail>()
            .Name("Grid_MCP_Detail_" + Model.id)
            .ToolBar(toolbar =>
            {
                toolbar.Create();
                toolbar.Save();
            })
            .Columns(columns =>
            {
                columns.Bound(c => c.id).Hidden(true);
                columns.Command(command => command.Destroy().IconClass("k-icon k-i-delete").Text(" ")).Width(56).MinResizableWidth(56);
                columns.Bound(c => c.codiceInterno).Width(200).Sticky(true);
                columns.Group(g => g
                    .Title("A cura del personale Marketing o dei Service Specialist Supervisor")
                    .Columns(mkss =>
                    {
                        mkss.Bound(c => c.descrizione).Width(300);
                        mkss.ForeignKey(c => c.UMBase, ds => ds.Read(r => r.Action("unitaMisura", "MCPDetailGrid")), "idMSEHI", "descrMSEHL").Width(300);
                        //mkss.Bound(c => c.UMBase).Width(300);
                        mkss.Bound(c => c.gruppoMerci).Width(300);
                        mkss.Bound(c => c.lineaProdotto).Width(300);
                        mkss.Bound(c => c.codiceTipo).Width(300);
                        mkss.Bound(c => c.voceCE).Width(300);
                        mkss.Bound(c => c.codiceValore).Width(300);
                        mkss.Bound(c => c.gestLottiMatricola).Width(300);
                        mkss.Bound(c => c.codiceEDMA).Width(150);
                        mkss.Bound(c => c.nomeFornitore).Width(150);
                        mkss.Bound(c => c.codiceProdottoFornitore).Width(150);
                        mkss.Bound(c => c.codiceCategoriaFornitore).Width(150);
                        mkss.Bound(c => c.pezziConf).Width(150);
                        mkss.Bound(c => c.infiammabile).Width(150);
                        mkss.Bound(c => c.ghiaccioSecco).Width(150);
                        mkss.Bound(c => c.ggMinEntrata).Width(150);
                        mkss.Bound(c => c.ggMinUscita).Width(150);
                        mkss.Bound(c => c.UMVendita).Width(150);
                        mkss.Bound(c => c.rapportoUMBV).Width(150);
                        mkss.Bound(c => c.royalty).Width(150);
                    }));
                columns.Group(g => g
                    .Title("A cura del Controllo di Gestione")
                    .Columns(ctgs =>
                    {
                        ctgs.Bound(c => c.costoAcquisto).Title("Costo acquisto").Width(150);
                        ctgs.Bound(c => c.valutaFatturazione).Title("Valuta di fatturazione").Width(150);
                        ctgs.Bound(c => c.codValuta).Title("Cod. Valuta").Width(150);
                        ctgs.Bound(c => c.prezzoMinimo).Title("Prezzo Minimo").Width(150);
                        ctgs.Bound(c => c.percProvvMinima).Title("% Provv minima").Width(150);
                        ctgs.Bound(c => c.prezzoSuggerito).Title("Prezzo Suggerito").Width(150);
                    }));

                columns.Group(g => g
                    .Title("A cura del MKTG o dei SSS")
                    .Columns(mkss =>
                    {
                        mkss.Bound(c => c.costoAcquisto).Title("Costo acquisto").Width(150);
                        mkss.Bound(c => c.valutaFatturazione).Title("Valuta di fatturazione").Width(150);
                        mkss.Bound(c => c.codValuta).Title("Cod. Valuta").Width(150);
                        mkss.Bound(c => c.prezzoMinimo).Title("Prezzo Minimo").Width(150);
                        mkss.Bound(c => c.percProvvMinima).Title("% Provv minima").Width(150);
                        mkss.Bound(c => c.prezzoListino).Title("Prezzo Listino").Width(150);
                        mkss.Bound(c => c.percProvvMassima).Title("% Provv max").Width(150);
                    }));

                columns.Group(g => g
                    .Title("A cura di AAT")
                    .Columns(aat =>
                    {
                        aat.Bound(c => c.codiceWindSat).Title("Cod. Winsat").Width(150);
                    }));
                columns.Bound(c => c.idStato).Title("Stato").Width(150);
                })
            .Editable(editable => {
                editable.Mode(GridEditMode.InCell);
                editable.CreateAt(GridInsertRowPosition.Bottom);
            })
            .Sortable()
            .Scrollable()
            .Resizable(resizable => resizable.Columns(true))
            .Filterable()
            .DataSource(dataSource => dataSource
                .Ajax()
                .Batch(true)
                .ServerOperation(false)
                .Events(events => events.Error("error_handler"))
                .Model(model => model.Id(p => p.id))
                .Read(action => action.Action("Read", "MCPDetailGrid", new { idHeader = Model.id }))
                .Create(action => action.Action("Create", "MCPDetailGrid", new { idHeader = Model.id }))
                .Update(action => action.Action("Update", "MCPDetailGrid"))
                .Destroy(action => action.Action("Destroy", "MCPDetailGrid"))
            )
            .NoRecords("Nessun prodotto presente")
            .Navigatable()
        )}

 

[~/Views/Shared/EditorTemplates/GridForeignKey.cshtml]

@(
 Html.Kendo().DropDownListFor(m => m)
        .BindTo((SelectList)ViewData[ViewData.TemplateInfo.GetFullHtmlFieldName("") + "_Data"])
        .ValuePrimitive(true)
)

I tried with/without  ValuePrimitive and with/without @model object

 

[Models]

Where the data are used:

    [MetadataType(typeof(MCP_DetailMetaData))]
    public partial class MCP_Detail: IDisposable
    {
        private MCPEntities MCPDB = new MCPEntities();

        public class MCP_DetailMetaData
        {
            public int id { get; set; }

            public int idMCP { get; set; }
            
            [Required, MaxLength(10), DisplayName("Codice Interno")]
            public string codiceInterno { get; set; }

            [Required, MaxLength(40), DisplayName("Descrizione")]
            public string descrizione { get; set; }

            [Required, DisplayName("U.M. Base")]
            public string UMBase { get; set; }

            [Required, MaxLength(3), DisplayName("Gr. Merci")]

....

Where the data come from:

    public partial class MCP_Unita_Misura
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public MCP_Unita_Misura()
        {
            this.MCP_Detail = new HashSet<MCP_Detail>();
        }

        public string idMSEHI { get; set; }
        public string idMSEH3 { get; set; }
        public string idMSEH6 { get; set; }
        public string MSEHT { get; set; }
        public string descrMSEHL { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<MCP_Detail> MCP_Detail { get; set; }
    }

 

[Other]

The FK exists also in the DB and in the Model        

 

 

Thanks in advance

 

Cristian

Cristian
Top achievements
Rank 1
Iron
 answered on 20 Sep 2022
1 answer
72 views

Hello,

I have declared a column in a kendo grid as foreignkey,  data to be selected is set with as follows:

 columns.ForeignKey(mo => mo.CodKit, (System.Collections.IEnumerable)ViewBag.listKitMuestra, "idKit", "Descripcion").Title("Fabricante de Kit").Width(120);

where idKit is an integer and Descripcion is a string var.

 

The objects presented in kendoGrid have the CodKit field defined as int? and when I Create a row (inline edition used) when save button clicked, the value for CodKit is not sent in the objetct to controller.  If is an edition of a row with no value for this field and it´s setted to an option of the dropdownlist, kendoGrid acts as it was not changes in row an even not call to controller.  Ignores that column.

Only works if row has yet value  for this column when load items from database and you change the value selecting from dropdownlist another value, in this case is sent to controller in the objetct when update button is clicked.

I use incell dropdownlist with int values in several kendoGrids and no problem.  But this case with int? is not working correctly or i´m doing something wrong.

Thanks

Best regards,.

 

 

Eyup
Telerik team
 answered on 15 Sep 2022
Narrow your results
Selected tags
Tags
+? more
Top users last month
Patrick
Top achievements
Rank 1
Iron
Iron
Iron
MIS
Top achievements
Rank 1
Ross
Top achievements
Rank 1
Marcin
Top achievements
Rank 1
Iron
Iron
Sean
Top achievements
Rank 2
Iron
Want to show your ninja superpower to fellow developers?
Top users last month
Patrick
Top achievements
Rank 1
Iron
Iron
Iron
MIS
Top achievements
Rank 1
Ross
Top achievements
Rank 1
Marcin
Top achievements
Rank 1
Iron
Iron
Sean
Top achievements
Rank 2
Iron
Want to show your ninja superpower to fellow developers?
Want to show your ninja superpower to fellow developers?