How to return INT in ejs-dropdownlist (Dialog template, Grid)

Hello,

I have a DataGrid with a custom Dialog Template including a ejs-dropdownlist, The datasource of this dropdown is a List:

Model:
public List<ddList> PersonGroup { get; } = new List<ddList>
        {
            new ddList { Value = 0, Text = "a" },
            new ddList { Value = 1, Text = "b" },
            new ddList { Value = 2, Text = "c" },
            new ddList { Value = 3, Text = "d" },
            new ddList { Value = 4, Text = "e" },
            new ddList { Value = 5, Text = "f" },
            new ddList { Value = 6, Text = "g" },
            new ddList { Value = 7, Text = "h" },
            new ddList { Value = 8, Text = "i" },

        };
    }

    public partial class ddList
    {
            public int Value { get; set; }
            public string Text { get; set; }

      }

Contoller:
public IActionResult EditPartial([FromBody] CRUDModel<Personal> value)
        {
            ViewBag.dataSource = objPersonal.GetAllPersonal().ToList();
            ViewBag.PersonGroup = objPersonal.PersonGroup;
            return PartialView("EditPartial", value.Value);
        }

public IActionResult Update([FromBody]CRUDModel<Personal> value)
        {
            objPersonal.UpdatePersonal(value.Value);
            return Json(value.Value);
        }

EditPartial.cshtml

<ejs-dropdownlist id="Personengruppe"  value="@Model.Personengruppe" dataSource="@ViewBag.PersonGroup" popupHeight="300px">
            <e-dropdownlist-fields text="Text" value="Value"></e-dropdownlist-fields>
        </ejs-dropdownlist> 

On POST(Save button) I get a 500 error (because the parameter of "Personengruppe" is a string:  "Personengruppe":"2")
So the "[FromBody]CRUDModel<Personal> value" on update is NULL an i get an error.

When i use a input like:
<input asp-for="Personengruppe" [email protected] type="number" />
So the Value will be posted as INT and everything is ok.

How can i post the value of my dropdownlist as INT?


5 Replies 1 reply marked as answer

PK Prasanna Kumar Viswanathan Syncfusion Team August 25, 2020 02:36 PM UTC

Hi Alexander, 
 
Thanks for contacting Syncfusion support. 
 
Based on your query you need to return the integer value from the dropdownlist. In this you also mentioned that you get a 500 error and root cause of an error you have mentioned that the parameter is passed as a string value. To proceed with this query, we need the following details 
 
1. Share the complete Grid rendering code. 
 
2. Share the data that you have bounded for the dropdown column. 
 
3. Syncfusion Package Version. 
 
Regards, 
Prasanna Kumar N.S.V 



AL alexander.sirotkin August 26, 2020 10:29 AM UTC

Hi Prasanna,
1. Syncfusion Version is 18.1.0.42

MODEL:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;

namespace APP.Models
{
    public class Product
    {
        public int Id { get; set; }
        [Display(Name = "Productname")]
        public string Name { get; set; }
        public int Group_Id { get; set; }
        public DateTime? DateCreated { get; set; }
        [DisplayFormat(DataFormatString = "{0:C2}", ApplyFormatInEditMode = true)]
        public double Price { get; set; }
        public bool Active { get; set; }

        public IEnumerable<Product> ProductList()
        {
            List<Product> ProductList = new List<Product>
            {
                new Product { Id = 1, Name = "B234" , Group_Id = 1, DateCreated= new DateTime(2020,06,20), Price = 22.15, Active = true},
                new Product { Id = 2, Name = "GR23" , Group_Id = 2,  Price = 28, Active = false },
                new Product { Id = 3, Name = "dB86", Group_Id = 3, Price = 2.70, Active = true },

            };
            return ProductList;
        }

        public void AddProduct(Product Product)
        {
            List<Product> products = (List<Product>)ProductList();
            products.Add(new Product() { Id = Product.Id, Name = Product.Name, Group_Id = Product.Group_Id, DateCreated = Product.DateCreated, Price = Product.Price, Active = Product.Active });

        }

        public void UpdateProduct(Product Product)
        {

            List<Product> coll = (List<Product>)ProductList();
            var found = coll.FirstOrDefault(c => c.Id == Product.Id);
            found.Name = Product.Name;
            found.Group_Id = Product.Group_Id;
            found.DateCreated = Product.DateCreated;
            found.Price = Product.Price;
            found.Active = Product.Active;

        }

        public List<ddList> ProductGroup { get; } = new List<ddList>
        {
            new ddList { Value = 0, Text = "a" },
            new ddList { Value = 1, Text = "b" },
            new ddList { Value = 2, Text = "c" },
            new ddList { Value = 3, Text = "d" },
            new ddList { Value = 4, Text = "e" }

        };

    }

    public partial class ddList
    {
        public int Value { get; set; }
        public string Text { get; set; }

    }
}

CONTROLLER:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using APP.Models;
using Syncfusion.EJ2.Base;

namespace APP.Controllers
{
    public class ProductController : Controller
    {
        Product objProduct = new Product();
        public IActionResult ProductGrid() // RemoteAdapter
        {
            List<Product> personal = new List<Product>();
            personal = objProduct.ProductList().ToList();
            var data = personal;
            ViewBag.dataSource = data.ToArray();
            ViewBag.ProductGroup = objProduct.ProductGroup;
            return View();
        }

        public IActionResult EditPartial([FromBody] CRUDModel<Product> value)
        {
            ViewBag.dataSource = objProduct.ProductList().ToList();
            ViewBag.ProductGroup = objProduct.ProductGroup;
            return PartialView("EditPartial", value.Value);
        }

        public IActionResult AddPartial([FromBody] CRUDModel<Product> value)
        {
            ViewBag.dataSource = objProduct.ProductList().ToList();
            ViewBag.ProductGroup = objProduct.ProductGroup;
            return PartialView("AddPartial", value.Value);
        }

        public JsonResult Update([FromBody] CRUDModel<Product> value)
        {

            objProduct.UpdateProduct(value.Value);
            return Json(value.Value);
        }

        public IActionResult Insert([FromBody] CRUDModel<Product> value)
        {
            objProduct.AddProduct(value.Value);
            return Json(value.Value);
        }

    }
}



AL alexander.sirotkin August 26, 2020 10:42 AM UTC

GRID View:
@using Syncfusion.EJ2
@{
    ViewData["Title"] = "ProductGrid";

}

<h2>Product</h2>


<div class="control-section">
    <ejs-grid id="Grid"
              actionComplete="actionComplete"
              width="auto"
              height="500px"
              enableInfiniteScrolling="false" allowPaging="true"
              allowTextWrap="true"
              allowResizing="false"
              enableHover="true"
              allowSorting="true"
              allowMultiSorting="true"
              toolbar="@(new List<string>() { "Add", "Edit",  "Update", "Cancel", "Search" })">
        <e-data-manager json="@ViewBag.dataSource" adaptor="RemoteSaveAdaptor" insertUrl="/Product/Insert" updateUrl="/Product/Update"></e-data-manager>
        <e-grid-editSettings allowAdding="true"  allowEditing="true" mode="Dialog" template="#dialogtemplate"></e-grid-editSettings>
        <e-grid-columns>
            <e-grid-column field="Id" headerText="ID" isPrimaryKey="true" visible="false" allowEditing="false"></e-grid-column>
            <e-grid-column field="Name" headerText="Product name" allowResizing="false" ></e-grid-column>
            <e-grid-column field="DateCreated" format="dd.MM.yyyy" allowResizing="false"  headerText="Creation date"></e-grid-column>
            <e-grid-column field="Group_Id" headerText="Productgroup" foreignKeyField="Value" foreignKeyValue="Text" dataSource="ViewBag.ProductGroup"></e-grid-column>
            <e-grid-column field="Price" headerText="Price" allowResizing="false" ></e-grid-column>
            <e-grid-column field="Active" headerText="Active" displayAsCheckBox="true" textAlign="Center" type="boolean"></e-grid-column>


        </e-grid-columns>
    </ejs-grid>


</div>

<script id='dialogtemplate' type="text/x-template">
    <div id="dialogTemp">
    </div>
</script>

<script>
        function actionComplete(args) {
            if (args.requestType === 'beginEdit' || args.requestType === 'add') {
                var dialog = args.dialog;
                dialog.header = args.requestType === 'beginEdit' ? 'Data from ' + args.rowData['Name'] : 'New Product';
                let spinner = ej.popups.createSpinner({ target: args.dialog.element });
                ej.popups.showSpinner(args.dialog.element);
                if (args.requestType === 'beginEdit') {
                    var ajax = new ej.base.Ajax({
                        url: "@Url.Action("Editpartial", "Product")", //render the partial view
                        type: "POST",
                        contentType: "application/json",
                        data: JSON.stringify({ value: args.rowData })
                    });
                    ajax.send().then(function (data) {
                        appendElement(data, args.form); //Render the edit form with selected record
                        //args.form.elements.namedItem('Id').focus();
                        ej.popups.hideSpinner(args.dialog.element);
                    }).catch(function (xhr) {
                        console.log(xhr);
                        ej.popups.hideSpinner(args.dialog.element);
                    });
                }
                if (args.requestType === 'add') {
                    var ajax = new ej.base.Ajax({
                        url: "@Url.Action("Addpartial","Product")", //render the partial view
                        type: "POST",
                        contentType: "application/json",
                        data: JSON.stringify({ value: args.rowData })
                    });
                    ajax.send().then(function (data) {
                        appendElement(data, args.form); //Render the edit form with selected record
                        //args.form.elements.namedItem('Id').focus();
                        ej.popups.hideSpinner(args.dialog.element);
                    }).catch(function (xhr) {
                        console.log(xhr);
                        ej.popups.hideSpinner(args.dialog.element);
                    });
                }
            }
        }

        function appendElement(elementString, form) {
            form.querySelector("#dialogTemp").innerHTML = elementString;
            var script = document.createElement('script');
            script.type = "text/javascript";
            var serverScript = form.querySelector("#dialogTemp").querySelector('script');
            script.textContent = serverScript.innerHTML;
            document.head.appendChild(script);
            serverScript.remove();
        }
</script>

PartialEditView:
@model APP.Models.Product
@using Syncfusion.EJ2
<div>
    <div class="form-row">
        <div class="form-group col-md-4">
            <div class="e-float-input e-control-wrapper">
                <input asp-for="Id" [email protected]() disabled type='text' />
                <span class="e-float-line"></span>
                <label asp-for="Id" class="e-float-text e-label-top">Id</label>
            </div>
        </div>

        <div class="form-group col-md-4">
            <div class="e-float-input e-control-wrapper">
                <input asp-for="Name" [email protected] type="text" />
                <span class="e-float-line"></span>
                <label asp-for="Name" class="e-float-text e-label-top">Productname</label>
            </div>
        </div>
        <div class="form-group col-md-4">
            <ejs-datepicker id="DateCreated" [email protected] placeholder="Creation date" firstDayOfWeek="1" floatLabelType="Always"></ejs-datepicker>
        </div>
    </div>

    <div class="form-row">
        <div class="form-group col-md-6">
            <ejs-dropdownlist id="Group_Id" [email protected]_Id dataSource="@ViewBag.ProductGroup" placeholder="Productgroup" floatLabelType="Always" popupHeight="300px">
                <e-dropdownlist-fields text="Text" value="Value"></e-dropdownlist-fields>
            </ejs-dropdownlist>
        </div>
        <div class="form-group col-md-3">
            <ejs-numerictextbox id="Price" [email protected] format="C2" placeholder="Price" floatLabelType="Always"></ejs-numerictextbox>
        </div>
        <div class="form-group col-md-3">
            <ejs-checkbox id="Active" checked="@Model.Active" label="Active" change="onChange"></ejs-checkbox>          
            @* BUT THIS works as expected: <input type="checkbox" name="Active" value="true" checked="@Model.Active" />*@
        </div>
    </div>
</div>
<ejs-scripts></ejs-scripts>

Problems (on Update POST ):
public JsonResult Update([FromBody] CRUDModel<Product> value) -> value = null
1. ejs-dropdownlist returns "Value" as String (Group_Id = "2")
Other Problems:
2. ejs-checkbox doesnt change the value on update
3. ejs-numerictextbox only returns an int (input: 23,75 on post: 23 or value= null)
4. ejs-datepicker when i chose 05.08.2020 in a datepicker the posted value is 04.08.2020 22:00:00



AG Ajith Govarthan Syncfusion Team August 31, 2020 04:15 PM UTC

Hi Alexander, 

Sorry for the delayed Response. 

Query: 1. ejs-dropdownlist returns "Value" as String (Group_Id = "2") 
 
Based on your requirement you want to sent integer values in the server side instead of string values  using the dropdown component. Based on that we have prepared sample in that we have shown the text values in the dropdown and saved the integer values in the dataSource. For your convenience we have attached the sample so please refer the sample for your reference. 

Code example: 
Index.cshtml 
 
<ejs-grid id="Grid" allowPaging="true" load="onLoad" actionBegin="actionBegin" actionComplete="actionComplete" toolbar="@(new List<string>() {"Add", "Edit", "Update", "Delete" })"> 
   
    <e-grid-editSettings allowAdding="true" allowDeleting="true" allowEditing="true" mode="Dialog" template='#dialogtemplate'></e-grid-editSettings> 
    <e-grid-columns> 
        <e-grid-column field="OrderID" headerText="Order ID" isPrimaryKey="true" textAlign="Right" width="100"></e-grid-column> 
        <e-grid-column field="CustomerID" headerText="Customer ID" type="string" validationRules="@(new { required= true })" width="120"></e-grid-column> 
        <e-grid-column field="Freight" headerText="Freight" textAlign="Right" format="C2" width="120"></e-grid-column> 
        <e-grid-column field="OrderDate" headerText="OrderDate" textAlign="Right" format="yMd" width="120"></e-grid-column> 
        <e-grid-column field="EmployeeID" headerText="EmployeeID" width="150"></e-grid-column> // dropdown column 
    </e-grid-columns> 
</ejs-grid> 
<script id='dialogtemplate' type="text/x-template"> 
    <div id="dialogTemp"> 
    </div> 
</script> 
 
<script> 
 
    function onLoad() { 
 
        this.dataSource = new ej.data.DataManager({ 
            json: @Html.Raw(Json.Serialize(ViewBag.DataSource)), 
            adaptor: new ej.data.RemoteSaveAdaptor(), 
            insertUrl: '/Home/Insert', 
            updateUrl: '/Home/Update', 
            removeUrl: '/Home/Delete' 
        }); 
 
    } 
 
    function actionBegin(args) { 
        if (args.requestType === 'save') { 
            console.log(args); 
        } 
    } 
 
    function actionFailure(args) { 
        console.log(args); 
    } 
 
    function actionComplete(args) { 
 
         if (args.requestType === 'beginEdit' || args.requestType === 'add') { 
                let spinner = ej.popups.createSpinner({ target: args.dialog.element }); 
                ej.popups.showSpinner(args.dialog.element); 
                if (args.requestType === 'beginEdit') { 
                    var ajax = new ej.base.Ajax({ 
                        url: "@Url.Action("Editpartial", "Home")", //render the partial view 
                        type: "POST", 
                        contentType: "application/json", 
                        data: JSON.stringify({ value: args.rowData }) 
                    }); 
                    ajax.send().then(function (data) { 
                        appendElement(data, args.form); //Render the edit form with selected record 
                        args.form.elements.namedItem('CustomerID').focus(); 
                        ej.popups.hideSpinner(args.dialog.element); 
                    }).catch(function (xhr) { 
                        console.log(xhr); 
                        ej.popups.hideSpinner(args.dialog.element); 
                    }); 
                } 
             if (args.requestType === 'add') { 
 
                    var ajax = new ej.base.Ajax({ 
                        url: "@Url.Action("Addpartial","Home")", //render the partial view 
                        type: "POST", 
                        contentType: "application/json", 
                        data: JSON.stringify({ value: args.rowData }) 
                    }); 
                    ajax.send().then(function (data) { 
                        appendElement(data, args.form); //Render the edit form with selected record 
                        args.form.elements.namedItem('OrderID').focus(); 
                        ej.popups.hideSpinner(args.dialog.element); 
                    }).catch(function (xhr) { 
                        console.log(xhr); 
                        ej.popups.hideSpinner(args.dialog.element); 
                    }); 
                } 
            } 
    } 
 
    function appendElement(elementString, form) { 
        form.querySelector("#dialogTemp").innerHTML = elementString; 
        var script = document.createElement('script'); 
        script.type = "text/javascript"; 
        var serverScript = form.querySelector("#dialogTemp").querySelector('script'); 
        script.textContent = serverScript.innerHTML; 
        document.head.appendChild(script); 
        serverScript.remove(); 
    } 
</script> 



Query: ejs-numerictextbox only returns an int (input: 23,75 on post: 23 or value= null) 
 
Based on the attached code example we have prepared sample but we found everything works fine at our end for your convenience we have attached the sample and the screenshot so please refer them for your reference. 

Screenshot: 
 

 


Query:  ejs-datepicker when i chose 05.08.2020 in a datepicker the posted value is 04.08.2020 22:00:00 & ejs-checkbox doesnt change the value on update 
 
Currently we are validating in your requirement and we will update further details on 1st September 2020. 

Until then we appreciate your patience. 

Regards, 
Ajith G. 



AG Ajith Govarthan Syncfusion Team September 3, 2020 07:43 AM UTC

Hi Alexander,  

Sorry for the delayed Response. 

Query:  ejs-datepicker when i chose 05.08.2020 in a datepicker the posted value is 04.08.2020 22:00:00. 
 
By default in EJ2 Grid to get the object values in server-side we need to stringify the values in client-side. So, while stringifying the date value the time will be decreased based on our time zone which was the Javascript default behavior, so you have received one day difference in the server-side.   

Find the screenshot:  

   
But when you return the date value from controller to client side it will automatically increase the time based on your local timezone. This is the actual behavior of our EJ2 Grid component. 
 
Query: ejs-checkbox doesnt change the value on update 
 
Based on your query we have prepared sample and in that sample we have added the name attribute for the checkbox component to fetch the state of the checkbox component correctly to updated them in the datasource.  
 
For your convenience we have attached the sample so please refer the sample for your reference. 
 
Code example: 
DialogEditPartial.cshtml 
 
<div> 
    <div class="form-row"> 
        <div class="form-group col-md-6"> 
            <div class="e-float-input e-control-wrapper"> 
                <input asp-for="OrderID" value=@Model.OrderID.ToString() disabled type='text' /> 
                <span class="e-float-line"></span> 
                <label asp-for="OrderID" class="e-float-text e-label-top">Order ID</label> 
            </div> 
        </div> 
        <div class="form-group col-md-6"> 
            <div class="e-float-input e-control-wrapper"> 
                <input asp-for="CustomerID" value=@Model.CustomerID required="required" /> 
                <span class="e-float-line"></span> 
                <label asp-for="CustomerID" class="e-float-text e-label-top">Customer Name</label> 
            </div> 
        </div> 
    </div> 
 
    <div class="form-row"> 
        <div class="form-group col-md-6"> 
            <ejs-numerictextbox id="Freight" value=@Model.Freight format="C2" placeholder="Freight" floatLabelType="Always"></ejs-numerictextbox> 
        </div> 
        <div class="form-group col-md-4"> 
            <ejs-datepicker id="OrderDate" value=@Model.OrderDate placeholder="Order Date" firstDayOfWeek="1" floatLabelType="Always"></ejs-datepicker> 
        </div> 
    </div> 
    <div class="form-group col-md-6"> 
        <ejs-dropdownlist id="ShipCity" value=@Model.ShipCity dataSource="@ViewBag.datasource" placeholder="Ship City" floatLabelType="Always" popupHeight="300px"> 
            <e-dropdownlist-fields text="ShipCity" value="ShipCity"></e-dropdownlist-fields> 
        </ejs-dropdownlist> 
    </div> 
 
</div> 
<div class="form-row"> 
    <div class="form-group col-md-6"> 
        <ejs-dropdownlist id="EmployeeID" value="@Model.EmployeeID" dataSource="@ViewBag.drpData" placeholder="EmployeeID" floatLabelType="Always" popupHeight="300px"> 
            <e-dropdownlist-fields text="Text" value="Value"></e-dropdownlist-fields> 
        </ejs-dropdownlist> 
    </div> 
    <div class="form-group col-md-3"> 
        <ejs-checkbox id="Verified" checked="@Model.Verified" name="Verified" ></ejs-checkbox> 
 
    </div> 
</div> 
 
 
 
 
Please get back to us if you need further assistance. 
 
Regards, 
Ajith G. 


Marked as answer
Loader.
Up arrow icon